﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using System.IO;
//using Bespoke.Common.Osc;
using System.Net;
using System.Threading;
using Microsoft.Research.DynamicDataDisplay;
using Microsoft.Research.DynamicDataDisplay.DataSources;
using System.ComponentModel;
//using Nui.Vision;
using System.Windows.Media.Media3D;
using System.IO.IsolatedStorage;
using Visiblox.Charts;
using System.Windows.Media.Animation;
using System.Windows.Controls.Primitives;
using System.Collections;
using System.Xaml;
using System.ServiceModel;
using System.Collections.ObjectModel;
using System.Data;
using Microsoft.Research.Kinect.Nui;

namespace Loader
{
    /// <summary>
    /// Interaction logic for Window2.xaml
    /// </summary>
    public partial class Window2 : Window
    {
        //ShortCut Key
        /* F12: ReDownload Data
         * F11: Toggle visiblility label for elbow value
         */

        # region variables
        Label lblLeftElbow = new Label();
        bool showJointLabel = false;
        #region static variables
        List<patient> allOwnPatient = new List<patient>();
        List<patient> allOthPatient = new List<patient>();
        string docname;
        patient p;
        List<ServiceReference2.problem> problemList;
        List<ServiceReference2.EXE> exeAssignedList;
        List<ServiceReference2.EXE> exeList;
        List<ServiceReference2.EXE> allExeList = new List<ServiceReference2.EXE>();
        List<ServiceReference2.session> patientSessionList;
        List<ServiceReference2.gamePlay> gamePlayList = new List<ServiceReference2.gamePlay>();
        List<ServiceReference2.session> allSessionOfPatientOfExeList = new List<ServiceReference2.session>();
        #endregion
        bool selectPatientMode = true;
        List<Image> jointList = new List<Image>();
        ServiceReference2.Service1Client svc = new ServiceReference2.Service1Client();
        int downloadOwnOtherCount = 0;

        List<Button> jointBtnList = new List<Button>();
        bool BWstarted = false;
        int currentProblemID = 0;

        //static List<ServiceReference2.EXE> exeList;
        List<Color> colurList = new List<Color>();

        System.Collections.ObjectModel.ObservableCollection<ServiceReference2.EXE> exeRecommendedListJoint = new System.Collections.ObjectModel.ObservableCollection<ServiceReference2.EXE>();
        System.Collections.ObjectModel.ObservableCollection<ServiceReference2.EXE> exeAssignedListJoint = new System.Collections.ObjectModel.ObservableCollection<ServiceReference2.EXE>();

        System.Collections.ArrayList al = new System.Collections.ArrayList(); //Fugl Meyer
        System.Collections.ArrayList scoring = new System.Collections.ArrayList(); //List of scoring
        System.Collections.ArrayList angleing = new System.Collections.ArrayList(); //List of pairs of angles
        System.Collections.ArrayList listofdif = new System.Collections.ArrayList(); //listofdif
        DateTime lowSystemTime = DateTime.Now;
        int dif = 0;

        bool xmlRead = false;

        string currentNavigationTag = "0";
        string beforetbx_joint = "";
        string beforetbx_joint_copy = "";

        private ServiceReference2.EXE selectedExe;
        ArrayList stageID = new ArrayList();
        int colorCount = 0;
        string stageName;




        # endregion
        #region offical kinect sdk variables
        Runtime nui;
        int totalFrames = 0;
        int lastFrames = 0;
        DateTime lastTime = DateTime.MaxValue;

        // We want to control how depth data gets converted into false-color data
        // for more intuitive visualization, so we keep 32-bit color frame buffer versions of
        // these, to be updated whenever we receive and process a 16-bit frame.
        const int RED_IDX = 2;
        const int GREEN_IDX = 1;
        const int BLUE_IDX = 0;
        byte[] depthFrame32 = new byte[320 * 240 * 4];


        Dictionary<JointID, Brush> jointColors = new Dictionary<JointID, Brush>() { 
            {JointID.HipCenter, new SolidColorBrush(Color.FromRgb(169, 176, 155))},
            {JointID.Spine, new SolidColorBrush(Color.FromRgb(169, 176, 155))},
            {JointID.ShoulderCenter, new SolidColorBrush(Color.FromRgb(168, 230, 29))},
            {JointID.Head, new SolidColorBrush(Color.FromRgb(200, 0,   0))},
            {JointID.ShoulderLeft, new SolidColorBrush(Color.FromRgb(79,  84,  33))},
            {JointID.ElbowLeft, new SolidColorBrush(Color.FromRgb(84,  33,  42))},
            {JointID.WristLeft, new SolidColorBrush(Color.FromRgb(255, 126, 0))},
            {JointID.HandLeft, new SolidColorBrush(Color.FromRgb(215,  86, 0))},
            {JointID.ShoulderRight, new SolidColorBrush(Color.FromRgb(33,  79,  84))},
            {JointID.ElbowRight, new SolidColorBrush(Color.FromRgb(33,  33,  84))},
            {JointID.WristRight, new SolidColorBrush(Color.FromRgb(77,  109, 243))},
            {JointID.HandRight, new SolidColorBrush(Color.FromRgb(37,   69, 243))},
            {JointID.HipLeft, new SolidColorBrush(Color.FromRgb(77,  109, 243))},
            {JointID.KneeLeft, new SolidColorBrush(Color.FromRgb(69,  33,  84))},
            {JointID.AnkleLeft, new SolidColorBrush(Color.FromRgb(229, 170, 122))},
            {JointID.FootLeft, new SolidColorBrush(Color.FromRgb(255, 126, 0))},
            {JointID.HipRight, new SolidColorBrush(Color.FromRgb(181, 165, 213))},
            {JointID.KneeRight, new SolidColorBrush(Color.FromRgb(71, 222,  76))},
            {JointID.AnkleRight, new SolidColorBrush(Color.FromRgb(245, 228, 156))},
            {JointID.FootRight, new SolidColorBrush(Color.FromRgb(77,  109, 243))}
        };
        #endregion


        public Window2()
        {
            InitializeComponent();
            patient p = new patient();
            //uncomment later


            //uncomment this if you start from this screen directly
            al.Clear();
            al.Add(11);
            al.Add(9);
            al.Add(2);
            al.Add(4);
            //try
            //{
            //    List<ServiceReference2.patient> patientList = svc.retrieveAllOwnPatients("Sunny");
            //    exeList = svc.retrieveAllEXEofExeType(1);
            //    foreach (ServiceReference2.patient p in patientList)
            //    {
            //        allOwnPatient.Add(new patient(p.Uid, p.LastName, p.FirstName, p.Age, p.ContactNum, p.Address1, p.Address2, p.Postcode, p.Doc, p.E_name, p.E_relationship, p.E_contactNum, p.ImagePath, p.DateOfBirth, p.Email, p.Gender, p.ContactNumHome, p.Title, p.Identifier, p.ContactNumWork, p.Country));
            //    }
            //}
            //catch (Exception ex)
            //{
            //}
            //preDownloadPatientList();
            //currentDetailLevel = 0;
            //currentPatientListNavigation = 1;
            //btn_otherPatient_MouseLeftButtonDown(btn_myPatient, null);
            //btn_detail_1.Source = new BitmapImage(new Uri("zoomPointSelected.png", UriKind.Relative));
            //svc.retrieveAllOthPatientsCompleted += new EventHandler<ServiceReference2.retrieveAllOthPatientsCompletedEventArgs>(svc_retrieveAllOthPatientsCompleted);
            //svc.retrieveAllOthPatientsAsync("Sunny");
            //compulsoryWork();
            //svc.retrievePatientCompleted += new EventHandler<ServiceReference2.retrievePatientCompletedEventArgs>(svc_retrievePatientCompleted);
            ////svc.retrievePatientAsync(1);
        }

        void svc_retrievePatientCompleted(object sender, ServiceReference2.retrievePatientCompletedEventArgs e)
        {
            if (e.Error == null)
            {
                ServiceReference2.patient tempPatient = e.Result;
                patient temp = new patient(tempPatient.Uid, tempPatient.LastName, tempPatient.FirstName, tempPatient.ContactNum, tempPatient.Address1, tempPatient.Address2, tempPatient.Postcode, tempPatient.Doc, tempPatient.E_name, tempPatient.E_relationship, tempPatient.E_contactNum, tempPatient.ImagePath, tempPatient.DateOfBirth, tempPatient.Email, tempPatient.Gender, tempPatient.ContactNumHome, tempPatient.Title, tempPatient.ContactNumWork, tempPatient.Country, tempPatient.PlaceID, tempPatient.E_address1, tempPatient.E_address2, tempPatient.E_postalcode, tempPatient.PlaceName);

                compulsoryWork();

                doWorkAfterPatientSelected(temp);
            }
        }

        public Window2(string dname, MainWindow mainWindow)
        {
            InitializeComponent();
            patientListItem temp = new patientListItem();
            temp.resetCount();
            //if (docname != dname)
            //{
            docname = dname;

            al.Clear();
            al.Add(4);
            al.Add(2);
            al.Add(11);
            al.Add(9);

            startLoading();
            //try
            //{
            svc.retrieveAllOwnPatientsCompleted += new EventHandler<ServiceReference2.retrieveAllOwnPatientsCompletedEventArgs>(svc_retrieveAllOwnPatientsCompleted);
            svc.retrieveAllOwnPatientsAsync(dname);
            svc.retrieveAllEXEofExeTypeCompleted += new EventHandler<ServiceReference2.retrieveAllEXEofExeTypeCompletedEventArgs>(svc_retrieveAllEXEofExeTypeCompleted);
            svc.retrieveAllEXEofExeTypeAsync(1);
            //exeList = svc.retrieveAllEXEofExeType(1);
            //List<ServiceReference2.patient> patientList = svc.retrieveAllOwnPatients(dname);
            //exeList = svc.retrieveAllEXEofExeType(1);
            //foreach (ServiceReference2.patient p in patientList)
            //{
            //    allOwnPatient.Add(new patient(p.Uid, p.LastName, p.FirstName, p.ContactNum, p.Address1, p.Address2, p.Postcode, p.Doc, p.E_name, p.E_relationship, p.E_contactNum, p.ImagePath, p.DateOfBirth, p.Email, p.Gender, p.ContactNumHome, p.Title, p.ContactNumWork, p.Country, p.PlaceID, p.E_address1, p.E_address2, p.E_postalcode, p.PlaceName));
            //}
            //}
            //catch (Exception)
            //{
            //}

            //preDownloadPatientList();
            //currentDetailLevel = 0;
            //currentPatientListNavigation = 1;
            //btn_otherPatient_MouseLeftButtonDown(btn_myPatient, null);
            //btn_detail_1.Source = new BitmapImage(new Uri("zoomPointSelected.png", UriKind.Relative));
            svc.retrieveAllOthPatientsCompleted += new EventHandler<ServiceReference2.retrieveAllOthPatientsCompletedEventArgs>(svc_retrieveAllOthPatientsCompleted);
            svc.retrieveAllOthPatientsAsync(dname);
            //}
            //else
            //{
            //    //preDownloadPatientList();
            //    currentDetailLevel = 0;
            //    currentPatientListNavigation = 1;
            //    btn_otherPatient_MouseLeftButtonDown(btn_myPatient, null);
            //}


            btn_detail_1.Source = new BitmapImage(new Uri("zoomPointSelected.png", UriKind.Relative));

            lblDocname.Content = dname;

            compulsoryWork();
        }

        void svc_retrieveAllEXEofExeTypeCompleted(object sender, ServiceReference2.retrieveAllEXEofExeTypeCompletedEventArgs e)
        {
            if (e.Error == null)
            {
                exeList = e.Result;
            }
        }

        void svc_retrieveAllOwnPatientsCompleted(object sender, ServiceReference2.retrieveAllOwnPatientsCompletedEventArgs e)
        {
            if (e.Error == null)
            {
                List<ServiceReference2.patient> patientList = e.Result;
                //exeList = svc.retrieveAllEXEofExeType(1);
                foreach (ServiceReference2.patient p in patientList)
                {
                    allOwnPatient.Add(new patient(p.Uid, p.LastName, p.FirstName, p.ContactNum, p.Address1, p.Address2, p.Postcode, p.Doc, p.E_name, p.E_relationship, p.E_contactNum, p.ImagePath, p.DateOfBirth, p.Email, p.Gender, p.ContactNumHome, p.Title, p.ContactNumWork, p.Country, p.PlaceID, p.E_address1, p.E_address2, p.E_postalcode, p.PlaceName));
                }
                downloadOwnOtherCount++;
                if (downloadOwnOtherCount == 2)
                {
                    //do work...
                    preDownloadPatientList();
                }
            }

        }

        void compulsoryWork()
        {
            # region add color into list
            //colurList.Add(Colors.Red);
            //colurList.Add(Colors.Gold);
            colurList.Add(Colors.DeepPink);
            colurList.Add(Colors.Black);
            colurList.Add(Colors.Brown);
            colurList.Add(Colors.DarkBlue);
            colurList.Add(Colors.Crimson);
            //colurList.Add(Colors.SpringGreen);
            colurList.Add(Colors.DarkCyan);
            colurList.Add(Colors.DarkGreen);
            colurList.Add(Colors.DarkMagenta);
            colurList.Add(Colors.DarkOrange);
            colurList.Add(Colors.DarkViolet);
            colurList.Add(Colors.SandyBrown);
            colurList.Add(Colors.Salmon);
            colurList.Add(Colors.SlateGray);
            colurList.Add(Colors.SkyBlue);
            colurList.Add(Colors.RoyalBlue);
            colurList.Add(Colors.Purple);
            colurList.Add(Colors.Plum);
            colurList.Add(Colors.Pink);
            colurList.Add(Colors.PeachPuff);
            colurList.Add(Colors.PaleVioletRed);
            colurList.Add(Colors.PaleGoldenrod);
            colurList.Add(Colors.Orchid);

            colurList.Add(Colors.MediumTurquoise);
            colurList.Add(Colors.Maroon);
            colurList.Add(Colors.LimeGreen);
            colurList.Add(Colors.LightYellow);
            colurList.Add(Colors.Green);
            # endregion

            # region add image into a list
            jointList.Add(joint_1);
            jointList.Add(joint_2);
            jointList.Add(joint_3);
            jointList.Add(joint_4);
            jointList.Add(joint_5);
            jointList.Add(joint_6);
            jointList.Add(joint_7);
            jointList.Add(joint_8);
            jointList.Add(joint_9);
            jointList.Add(joint_10);
            jointList.Add(joint_11);
            jointList.Add(joint_12);
            jointList.Add(joint_13);
            jointList.Add(joint_14);

            //extra
            jointList.Add(joint_15);
            jointList.Add(joint_16);
            jointList.Add(joint_17);
            jointList.Add(joint_18);
            jointList.Add(joint_19);
            jointList.Add(joint_21);
            jointList.Add(joint_22);
            jointList.Add(joint_23);
            jointList.Add(joint_24);
            jointList.Add(joint_25);
            jointList.Add(joint_26);
            jointList.Add(joint_27);
            jointList.Add(joint_28);
            #endregion

            # region add button into a list
            jointBtnList.Add(btn_joint_1);
            jointBtnList.Add(btn_joint_2);
            jointBtnList.Add(btn_joint_3);
            jointBtnList.Add(btn_joint_4);
            jointBtnList.Add(btn_joint_5);
            jointBtnList.Add(btn_joint_6);
            jointBtnList.Add(btn_joint_7);
            jointBtnList.Add(btn_joint_8);
            jointBtnList.Add(btn_joint_9);
            jointBtnList.Add(btn_joint_10);
            jointBtnList.Add(btn_joint_11);
            jointBtnList.Add(btn_joint_12);
            jointBtnList.Add(btn_joint_13);
            jointBtnList.Add(btn_joint_14);
            jointBtnList.Add(btn_joint_15);
            jointBtnList.Add(btn_joint_16);
            jointBtnList.Add(btn_joint_17);
            jointBtnList.Add(btn_joint_18);
            jointBtnList.Add(btn_joint_19);
            jointBtnList.Add(btn_joint_20);
            jointBtnList.Add(btn_joint_21);
            jointBtnList.Add(btn_joint_22);
            jointBtnList.Add(btn_joint_23);
            jointBtnList.Add(btn_joint_24);
            jointBtnList.Add(btn_joint_25);
            jointBtnList.Add(btn_joint_26);
            jointBtnList.Add(btn_joint_27);
            jointBtnList.Add(btn_joint_28);
            # endregion
        }

        void svc_retrieveAllOthPatientsCompleted(object sender, ServiceReference2.retrieveAllOthPatientsCompletedEventArgs e)
        {
            try
            {
                List<ServiceReference2.patient> patientList = e.Result;
                foreach (ServiceReference2.patient p in patientList)
                {
                    allOthPatient.Add(new patient(p.Uid, p.LastName, p.FirstName, p.ContactNum, p.Address1, p.Address2, p.Postcode, p.Doc, p.E_name, p.E_relationship, p.E_contactNum, p.ImagePath, p.DateOfBirth, p.Email, p.Gender, p.ContactNumHome, p.Title, p.ContactNumWork, p.Country, p.PlaceID, p.E_address1, p.E_address2, p.E_postalcode, p.PlaceName));
                }

                downloadOwnOtherCount++;
                if (downloadOwnOtherCount == 2)
                {
                    //do work...
                    preDownloadPatientList();
                }
                //this.Dispatcher.BeginInvoke((Action)(() =>
                //{

                //}));
            }
            catch (NullReferenceException)
            { }
        }

        #region................................after patient is selected................................................

        private void doWorkAfterPatientSelected(patient patient1)
        {
            p = patient1;

            //fill up the data for patient information
            fillData();

            setPatientProblem();
            MemberwiseClone();
        }

        //fill up patient information
        private void fillData()
        {
            int age = new DateTime(DateTime.Now.Subtract(p.DateOfBirth).Ticks).Year - 1;
            addressLabel2.Address1 = p.E_address1;
            addressLabel2.Address2 = p.E_address2;
            addressLabel2.Postcode = p.E_postalcode;
            lbl_eRelationship.Text = p.E_relationship;
            addressLabel1.Address1 = p.Address1;
            addressLabel1.Address2 = p.Address2;
            DOBValue.Text = String.Concat(p.DateOfBirth.ToShortDateString(), " (", age.ToString(), ")");
            lbl_email.Text = p.Email;
            nameLabel1.FamilyName = p.LastName;
            if (p.Gender.ToLower().Equals("m"))
            {
                GenderValue.Text = Microsoft.Cui.Controls.PatientGender.Male.ToString();
            }
            else if (p.Gender.ToLower().Equals("f"))
            {
                GenderValue.Text = Microsoft.Cui.Controls.PatientGender.Female.ToString();
            }

            nameLabel1.GivenName = String.Concat(p.FirstName);
            lbl_mobile.Text = p.ContactNum;
            lbl_home.Text = p.ContactNumHome;
            nameLabel1.Name = p.FirstName;
            img_patient.Source = p.Image;
            addressLabel1.Postcode = p.Postcode;
            nameLabel1.Title = p.Title;
            IdentifierValue.Text = p.Uid.ToString();
            //contactLabel1.WorkPhoneNumber = p.ContactNumWork;
            addressLabel1.Country = p.Country;

            if (p.E_name == null && p.E_contactNum == null)
            {
                panel_caregiver.Visibility = Visibility.Collapsed;
            }
            else
            {
                if (p.E_name != null)
                    lbl_eName.Text = p.E_name;
                if (p.E_contactNum != null)
                    lbl_eMobile.Text = p.E_contactNum;
            }
            //lblErelation1.Text = p.E_relationship;
        }

        private void resetProblemTag()
        {
            btn_joint_1.Tag = "1"; joint_1.Tag = "1";
            btn_joint_2.Tag = "2"; joint_2.Tag = "2";
            btn_joint_3.Tag = "3"; joint_3.Tag = "3";
            btn_joint_4.Tag = "4"; joint_4.Tag = "4";
            btn_joint_5.Tag = "5"; joint_5.Tag = "5";
            btn_joint_6.Tag = "6"; joint_6.Tag = "6";
            btn_joint_7.Tag = "7"; joint_7.Tag = "7";
            btn_joint_8.Tag = "8"; joint_8.Tag = "8";
            btn_joint_9.Tag = "9"; joint_9.Tag = "9";
            btn_joint_10.Tag = "10"; joint_10.Tag = "10";
            btn_joint_11.Tag = "11"; joint_11.Tag = "11";
            btn_joint_12.Tag = "12"; joint_12.Tag = "12";
            btn_joint_13.Tag = "13"; joint_13.Tag = "13";
            btn_joint_14.Tag = "14"; joint_14.Tag = "14";

            //extra
            btn_joint_15.Tag = "1"; joint_15.Tag = "1";
            btn_joint_16.Tag = "2"; joint_16.Tag = "2";
            btn_joint_17.Tag = "3"; joint_17.Tag = "3";
            btn_joint_18.Tag = "4"; joint_18.Tag = "4";
            btn_joint_19.Tag = "5"; joint_19.Tag = "5";
            btn_joint_20.Tag = "6"; joint_20.Tag = "6";
            btn_joint_21.Tag = "7"; joint_21.Tag = "7";
            btn_joint_22.Tag = "8"; joint_22.Tag = "8";
            btn_joint_23.Tag = "9"; joint_23.Tag = "9";
            btn_joint_24.Tag = "10"; joint_24.Tag = "10";
            btn_joint_25.Tag = "11"; joint_25.Tag = "11";
            btn_joint_26.Tag = "12"; joint_26.Tag = "12";
            btn_joint_27.Tag = "13"; joint_27.Tag = "13";
            btn_joint_28.Tag = "14"; joint_28.Tag = "14";

            btn_joint_1.Visibility = Visibility.Visible;
            btn_joint_2.Visibility = Visibility.Visible;
            btn_joint_3.Visibility = Visibility.Visible;
            btn_joint_4.Visibility = Visibility.Visible;
            btn_joint_5.Visibility = Visibility.Visible;
            btn_joint_6.Visibility = Visibility.Visible;
            btn_joint_7.Visibility = Visibility.Visible;
            btn_joint_8.Visibility = Visibility.Visible;
            btn_joint_9.Visibility = Visibility.Visible;
            btn_joint_10.Visibility = Visibility.Visible;
            btn_joint_11.Visibility = Visibility.Visible;
            btn_joint_12.Visibility = Visibility.Visible;
            btn_joint_13.Visibility = Visibility.Visible;
            btn_joint_14.Visibility = Visibility.Visible;
            btn_joint_15.Visibility = Visibility.Visible;
            btn_joint_16.Visibility = Visibility.Visible;
            btn_joint_17.Visibility = Visibility.Visible;
            btn_joint_18.Visibility = Visibility.Visible;
            btn_joint_19.Visibility = Visibility.Visible;
            btn_joint_20.Visibility = Visibility.Visible;
            btn_joint_21.Visibility = Visibility.Visible;
            btn_joint_22.Visibility = Visibility.Visible;
            btn_joint_23.Visibility = Visibility.Visible;
            btn_joint_24.Visibility = Visibility.Visible;
            btn_joint_25.Visibility = Visibility.Visible;
            btn_joint_26.Visibility = Visibility.Visible;
            btn_joint_27.Visibility = Visibility.Visible;
            btn_joint_28.Visibility = Visibility.Visible;
            joint_1.Source = new BitmapImage(new Uri("jointFine.png", UriKind.Relative));
            joint_2.Source = new BitmapImage(new Uri("jointFine.png", UriKind.Relative));
            joint_3.Source = new BitmapImage(new Uri("jointFine.png", UriKind.Relative));
            joint_4.Source = new BitmapImage(new Uri("jointFine.png", UriKind.Relative));
            joint_5.Source = new BitmapImage(new Uri("jointFine.png", UriKind.Relative));
            joint_6.Source = new BitmapImage(new Uri("jointFine.png", UriKind.Relative));
            joint_7.Source = new BitmapImage(new Uri("jointFine.png", UriKind.Relative));
            joint_8.Source = new BitmapImage(new Uri("jointFine.png", UriKind.Relative));
            joint_9.Source = new BitmapImage(new Uri("jointFine.png", UriKind.Relative));
            joint_10.Source = new BitmapImage(new Uri("jointFine.png", UriKind.Relative));
            joint_11.Source = new BitmapImage(new Uri("jointFine.png", UriKind.Relative));
            joint_12.Source = new BitmapImage(new Uri("jointFine.png", UriKind.Relative));
            joint_13.Source = new BitmapImage(new Uri("jointFine.png", UriKind.Relative));
            joint_14.Source = new BitmapImage(new Uri("jointFine.png", UriKind.Relative));
            joint_15.Source = new BitmapImage(new Uri("jointFine.png", UriKind.Relative));
            joint_16.Source = new BitmapImage(new Uri("jointFine.png", UriKind.Relative));
            joint_17.Source = new BitmapImage(new Uri("jointFine.png", UriKind.Relative));
            joint_18.Source = new BitmapImage(new Uri("jointFine.png", UriKind.Relative));
            joint_19.Source = new BitmapImage(new Uri("jointFine.png", UriKind.Relative));
            joint_20.Source = new BitmapImage(new Uri("jointFine.png", UriKind.Relative));
            joint_21.Source = new BitmapImage(new Uri("jointFine.png", UriKind.Relative));
            joint_22.Source = new BitmapImage(new Uri("jointFine.png", UriKind.Relative));
            joint_23.Source = new BitmapImage(new Uri("jointFine.png", UriKind.Relative));
            joint_24.Source = new BitmapImage(new Uri("jointFine.png", UriKind.Relative));
            joint_25.Source = new BitmapImage(new Uri("jointFine.png", UriKind.Relative));
            joint_26.Source = new BitmapImage(new Uri("jointFine.png", UriKind.Relative));
            joint_27.Source = new BitmapImage(new Uri("jointFine.png", UriKind.Relative));
            joint_28.Source = new BitmapImage(new Uri("jointFine.png", UriKind.Relative));

            foreach (Image image in jointList)
            {
                image.MouseEnter -= iBad_MouseEnter;
                image.MouseLeave -= iBad_MouseLeave;
            }
            foreach (Button btn in jointBtnList)
            {
                btn.Click -= joint_btn_Click;
                btn.ToolTip = "Fine";
            }


        }

        // set problems of a patient (bad joint)
        private void setPatientProblem()
        {
            for (int i = 0; i < problemList.Count(); i++)
            {
                ServiceReference2.problem temp = problemList[i];
                int joint = Convert.ToInt16(temp.Joint);
                foreach (Image image in jointList)
                {
                    if (Convert.ToInt16(image.Tag) == joint)
                    {
                        // change the image
                        image.Source = new BitmapImage(new Uri("jointBad.png", UriKind.Relative));
                        image.MouseEnter += new MouseEventHandler(iBad_MouseEnter);
                        image.MouseLeave += new MouseEventHandler(iBad_MouseLeave);
                        image.Tag = temp.Uid;
                        continue;
                    }
                }
                foreach (Button btn in jointBtnList)
                {
                    if (Convert.ToInt16(btn.Tag) == joint)
                    {
                        btn.Click += new RoutedEventHandler(joint_btn_Click);
                        btn.Tag = temp.Uid;
                        btn.ToolTip = temp.Description;
                        continue;
                    }
                }
            }

            //hide the blue color joints
            foreach (Button btn in jointBtnList)
            {
                if (Convert.ToInt16(btn.Tag) <= 14)
                {
                    btn.Visibility = Visibility.Collapsed;
                }
            }
        }


        # region MouseEnter MouseLeave events for joints image
        void i_MouseLeave(object sender, MouseEventArgs e)
        {
            Image image = (Image)sender;
            image.Source = new BitmapImage(new Uri("jointFine.png", UriKind.Relative));
        }

        void i_MouseEnter(object sender, MouseEventArgs e)
        {
            Image image = (Image)sender;
            image.Source = new BitmapImage(new Uri("jointFineH.png", UriKind.Relative));
        }

        void iBad_MouseLeave(object sender, MouseEventArgs e)
        {
            Image image = (Image)sender;
            image.Source = new BitmapImage(new Uri("jointBad.png", UriKind.Relative));
        }

        void iBad_MouseEnter(object sender, MouseEventArgs e)
        {
            Image image = (Image)sender;
            image.Source = new BitmapImage(new Uri("jointBadH.png", UriKind.Relative));
        }
        #endregion

        void joint_btn_Click(object sender, RoutedEventArgs e)
        {

            int problemUID = Convert.ToInt16(((Button)sender).Tag);
            selectedProblemUID = problemUID;
            if (currentProblemID != problemUID)
            {
                if (spShow == false)
                {
                    spAngle0.Visibility = Visibility.Collapsed;
                    spAngle.Visibility = Visibility.Visible;
                    sp_severity.Visibility = Visibility.Visible;
                    spShow = true;
                }

                cbxTreatment.SelectedIndex = -1;
                cbxPerformance.SelectedIndex = -1;
                cbxYAxis.SelectedIndex = -1;

                cbxTreatment.ItemsSource = null;
                sp_Stage.Visibility = Visibility.Collapsed;
                sp_Attribute.Visibility = Visibility.Collapsed;
                stageName = "";
                selectedExe = null;
                currentProblemID = problemUID;
                setProblem(problemUID);
                setEXE(problemUID);

                if (allExeList.Count == 0)
                {
                    try
                    {
                        allExeList = svc.retrieveAllEXE();
                    }
                    catch (Exception)
                    { }
                }
                List<ServiceReference2.EXE> treatmentList = new List<ServiceReference2.EXE>();
                foreach (ServiceReference2.EXE x in allExeList)
                {
                    foreach (string joint in x.Tag)
                    {
                        if (joint == tbx_joint_Copy.Text)
                        {
                            treatmentList.Add(x);
                        }
                    }
                }

                treatmentList = treatmentList.Distinct().ToList();
                cbxTreatment.Items.Clear();
                foreach (ServiceReference2.EXE x in treatmentList)
                {
                    cbxTreatment.Items.Add(x.Name);
                }

                //foreach (ServiceReference2.problem p in problemList)
                //{
                //    foreach (ServiceReference2.EXE ex in allExeList)
                //    {
                //        if (p.Uid == problemUID)
                //        {
                //            cbxTreatment.Items.Add(ex.Name);//get name for id
                //        }
                //    }
                //}
                //delete this line
                //currentNavigationTag = "1";
                if (currentNavigationTag.Equals("0"))
                {
                    BrushConverter brush = new BrushConverter();

                    btn_treatmentManager.Foreground = (Brush)brush.ConvertFromString("#FF000000");
                    btn_treatmentManagerB.Background = (Brush)brush.ConvertFromString("#FFFFFFFF");

                    //btn_treatmentManager.Foreground = (Brush)brush.ConvertFromString("#FF000000");
                    //btn_treatmentManagerB.Background = (Brush)brush.ConvertFromString("#FFFFFFFF");


                    currentNavigationTag = "2";
                    //BitmapImage test2 = new BitmapImage(new Uri("KS_treatmentManagerBG.png", UriKind.Relative));
                    //ImageBrush brush2 = new ImageBrush();
                    //brush2.ImageSource = test2;
                    //btn_treatmentManagerB.Background = brush2;
                    //btn_treatmentManager.Height = 24;
                    panel_treatmentManager.Visibility = Visibility.Visible;
                }
            }
        }

        int selectedProblemUID;

        private void setProblem(int problemUID)
        {
            for (int i = 0; i < problemList.Count(); i++)
            {
                ServiceReference2.problem temp = problemList[i];
                if (temp.Uid == problemUID)
                {
                    tbx_joint_Copy.Text = temp.Joint;
                    tbx_joint.Text = temp.JointName;

                    //tbxReport.Text = "";
                    string[] parts = temp.Description.Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries);
                    //for (int i1 = 0; i1 < parts.Length; i1++)
                    //{
                    //    tbxReport.Text += parts[i1] + Environment.NewLine;
                    //}

                    //tbxNote.Text = "";
                    //parts = temp.Notes.Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries);
                    //for (int i1 = 0; i1 < parts.Length; i1++)
                    //{
                    //    tbxNote.Text += parts[i1] + Environment.NewLine;
                    //}

                    lblSever.Text = temp.Severity.ToString();

                    List<double> angle = new List<double>();
                    List<double> angleX = new List<double>();
                    List<double> angleY = new List<double>();
                    List<double> angleZ = new List<double>();

                    if (Convert.ToInt32(temp.Joint) == 2 || Convert.ToInt32(temp.Joint) == 3)
                    {
                        angleX = svc.getLatestAngle(10, p.Uid, Convert.ToInt32(temp.Joint), "X");
                        angleY = svc.getLatestAngle(10, p.Uid, Convert.ToInt32(temp.Joint), "Y");
                        angleZ = svc.getLatestAngle(10, p.Uid, Convert.ToInt32(temp.Joint), "Z");

                        lbxMaxAngle.Text = angleX[0].ToString() + ", " + angleY[0].ToString() + ", " + angleZ[0].ToString() + " (X, Y, Z)";
                        lbxMinAngle.Text = angleX[1].ToString() + ", " + angleY[1].ToString() + ", " + angleZ[1].ToString() + " (X, Y, Z)";
                    }
                    else if (Convert.ToInt32(temp.Joint) == 9 || Convert.ToInt32(temp.Joint) == 10)
                    {
                        angleX = svc.getLatestAngle(10, p.Uid, Convert.ToInt32(temp.Joint), "X");
                        angleZ = svc.getLatestAngle(10, p.Uid, Convert.ToInt32(temp.Joint), "Z");

                        lbxMaxAngle.Text = angleX[0].ToString() + ", " + angleZ[0].ToString() + " (X, Z)";
                        lbxMinAngle.Text = angleX[1].ToString() + ", " + angleZ[1].ToString() + " (X, Z)";
                    }
                    else
                    {
                        angle = svc.getLatestAngle(10, p.Uid, Convert.ToInt32(temp.Joint), "");
                        lbxMaxAngle.Text = angle[0].ToString();
                        lbxMinAngle.Text = angle[1].ToString();
                    }
                    // set the color for severity
                    int severity = 6 - temp.Severity;
                    pbrSever.Value = (severity * 20);
                    if (pbrSever.Value >= 60)
                    {
                        pbrSever.Foreground = Brushes.Red;
                    }
                    else if (pbrSever.Value < 60 && pbrSever.Value >= 20)
                    {
                        pbrSever.Foreground = Brushes.Yellow;
                    }
                    else
                    {
                        pbrSever.Foreground = Brushes.DarkGreen;
                    }
                }
            }
        }
        // set EXE for recommended and assigned
        private void setEXE(int problemUID)
        {
            //List<ServiceReference2.EXE> exeRecommendedListJoint = new List<ServiceReference2.EXE>();
            //List<ServiceReference2.EXE> exeAssignedListJoint = new List<ServiceReference2.EXE>();
            ServiceReference2.problem problem = new ServiceReference2.problem();

            foreach (ServiceReference2.problem p in problemList)
            {
                if (p.Uid == currentProblemID)
                {
                    problem = p;
                }
            }

            exeRecommendedListJoint.Clear();

            foreach (ServiceReference2.EXE exeRecommended in exeList)
            {
                foreach (String jointTemp in exeRecommended.Tag)
                {
                    if (jointTemp == problem.Joint)
                    {
                        exeRecommendedListJoint.Add(exeRecommended);
                    }
                }
            }

            exeAssignedListJoint.Clear();
            List<int> addedExeIDAssigned = new List<int>();
            List<ServiceReference2.EXE> exeTempList = exeRecommendedListJoint.Distinct().ToList();
            foreach (ServiceReference2.EXE exeAssigned in exeAssignedList)
            {
                foreach (String jointTemp in exeAssigned.Tag)
                {
                    if (jointTemp == problem.Joint)
                    {
                        if (!addedExeIDAssigned.Contains(exeAssigned.Uid))
                        {
                            exeAssignedListJoint.Add(exeAssigned);
                        }

                        addedExeIDAssigned.Add(exeAssigned.Uid);
                        foreach (ServiceReference2.EXE exeTemp in exeTempList)
                        {
                            if (exeTemp.Uid == exeAssigned.Uid)
                            {
                                exeRecommendedListJoint.Remove(exeTemp);
                                //toAdd.Add(exeAssigned.Name);
                            }
                        }
                    }
                }
            }

            //toAdd = toAdd.Distinct().ToList();
            //cbxTreatment.ItemsSource = toAdd;
            //List<ServiceReference2.EXE> tempexe = exeRecommendedListJoint.Except(exeAssignedListJoint).ToList();
            //exeRecommendedListJoint.Clear();
            //foreach (ServiceReference2.EXE exe in tempexe)
            //{

            //    exeRecommendedListJoint.Add(exe);
            //}

            //lbx_exe.ItemsSource = exeRecommendedListJoint;
            //lbx_exeAssigned.ItemsSource = exeAssignedListJoint;

            //lbx_exe.Items.Clear();
            //lbx_exeAssigned.Items.Clear();
            List<ServiceReference2.EXE> exeRecommendedListJointTemp = exeRecommendedListJoint.Distinct().ToList();
            List<ServiceReference2.EXE> exeAssignedListJointTemp = exeAssignedListJoint.Distinct().ToList();
            //foreach (ServiceReference2.EXE temp in exeRecommendedListJointTemp)
            //{
            //    exeItem exeitem = new exeItem(temp);
            //    lbx_exe.Items.Add(exeitem);
            //}
            List<int> exeAssignedIntList = new List<int>();
            foreach (ServiceReference2.EXE temp in exeAssignedListJointTemp)
            {
                //exeItem exeitem = new exeItem(temp);
                //lbx_exeAssigned.Items.Add(exeitem);
                exeAssignedIntList.Add(temp.Uid); // new
            }

            foreach (ServiceReference2.EXE temp in exeAssignedListJointTemp)
            {
                exeItem exeitem = new exeItem(temp);
                exeitem.lbl_exeDescription.Text = temp.Description;
                exeitem.lbl_exeName.Text = temp.Name;
                exeitem.btn_unassign.MouseEnter += new MouseEventHandler(btn_unassign_MouseEnter);
                exeitem.btn_unassign.MouseLeave += new MouseEventHandler(btn_unassign_MouseLeave);
                exeitem.btn_unassign.MouseLeftButtonDown += new MouseButtonEventHandler(btn_unassign_MouseLeftButtonDown);
                BrushConverter brush = new BrushConverter();
                if (exeAssignedIntList.Contains(temp.Uid))
                {
                    exeitem.tbx_content.Text = "ASSIGN";
                    exeitem.btn_unassign.Background = (Brush)brush.ConvertFromString("#FF91C6F7");
                }
                else
                {
                    exeitem.tbx_content.Text = "UNASSIGN";
                    exeitem.btn_unassign.Background = (Brush)brush.ConvertFromString("#FFFFC000");
                }
                sp_listExe.Children.Add(exeitem);
                exeitem.MouseLeftButtonDown += new MouseButtonEventHandler(exeitem_MouseLeftButtonDown);
                
            }

            foreach (ServiceReference2.EXE temp in exeRecommendedListJointTemp)
            {
                exeItem exeitem = new exeItem(temp);
                exeitem.lbl_exeDescription.Text = temp.Description;
                exeitem.lbl_exeName.Text = temp.Name;
                exeitem.btn_unassign.MouseEnter+=new MouseEventHandler(btn_unassign_MouseEnter);
                exeitem.btn_unassign.MouseLeave +=new MouseEventHandler(btn_unassign_MouseLeave);
                exeitem.btn_unassign.MouseLeftButtonDown += new MouseButtonEventHandler(btn_unassign_MouseLeftButtonDown);
                BrushConverter brush = new BrushConverter();
                if (exeAssignedIntList.Contains(temp.Uid))
                {
                    exeitem.tbx_content.Text = "ASSIGN";
                    exeitem.btn_unassign.Background = (Brush)brush.ConvertFromString("#FF91C6F7");
                }
                else
                {
                    exeitem.tbx_content.Text = "UNASSIGN";
                    exeitem.btn_unassign.Background = (Brush)brush.ConvertFromString("#FFFFC000");
                }
                sp_listExe.Children.Add(exeitem);
                exeitem.MouseLeftButtonDown += new MouseButtonEventHandler(exeitem_MouseLeftButtonDown);
                
                //sp_settings = exeitem.spSettings;
            }
        }
        bool gotClick = false;
        void btn_unassign_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            BrushConverter brush = new BrushConverter();
            //btn_treatmentAnalysisB.Background = (Brush)brush.ConvertFromString("#FFFFFFFF");
            Border btn_unassign = (Border)sender;
            TextBlock tbx_content = (TextBlock)btn_unassign.Child;
            if (tbx_content.Text == "ASSIGN")
            {
                tbx_content.Text = "ASSIGN";
                btn_unassign.Background = (Brush)brush.ConvertFromString("#FF91C6F7");
            }
            else
            {
                tbx_content.Text = "UNASSIGN";
                btn_unassign.Background = (Brush)brush.ConvertFromString("#FFFFC000");
               
            }
            gotClick = true;
        }

        void btn_unassign_MouseLeave(object sender, MouseEventArgs e)
        {
            BrushConverter brush = new BrushConverter();
            //btn_treatmentAnalysisB.Background = (Brush)brush.ConvertFromString("#FFFFFFFF");
            Border btn_unassign = (Border)sender;
            TextBlock tbx_content = (TextBlock)btn_unassign.Child;
            if (gotClick == false)
            {
                if (tbx_content.Text == "ASSIGN")
                {
                    tbx_content.Text = "UNASSIGN";
                    btn_unassign.Background = (Brush)brush.ConvertFromString("#FFFFC000");
                }
                else
                {
                    tbx_content.Text = "ASSIGN";
                    btn_unassign.Background = (Brush)brush.ConvertFromString("#FF91C6F7");
                }
            }
            else
            {
                gotClick = false;
            }
        }

        void btn_unassign_MouseEnter(object sender, MouseEventArgs e)
        {
            gotClick = false;
            BrushConverter brush = new BrushConverter();
            //btn_treatmentAnalysisB.Background = (Brush)brush.ConvertFromString("#FFFFFFFF");
            Border btn_unassign = (Border)sender;
            TextBlock tbx_content = (TextBlock)btn_unassign.Child;
            if (tbx_content.Text == "ASSIGN")
            {
                tbx_content.Text = "UNASSIGN";
                btn_unassign.Background = (Brush)brush.ConvertFromString("#FFFFC000");
            }
            else
            {
                tbx_content.Text = "ASSIGN";
                btn_unassign.Background = (Brush)brush.ConvertFromString("#FF91C6F7");
            }
        }


        void exeitem_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            sp_exeInfo.Visibility = Visibility.Visible;
            lbl_movement.Visibility = Visibility.Visible;
            try
            {
                exeItem exeitem = (exeItem)sender;
                lbl_exeName.Text = exeitem.lbl_exeName.Text;
                ServiceReference2.EXE exe = exeitem.selectedExe;

                #region test for settings
                spSettings.Children.Clear();
                if (exe.CustKey != null && exe.CustKey.Count != 0)
                {
                    try
                    {
                        //lbl_setting.Visibility = Visibility.Visible;
                        foreach (string key in exe.CustKey)
                        {
                            StackPanel stackpanel = new StackPanel();
                            stackpanel.Margin = new Thickness(0, 2, 0, 2);
                            stackpanel.Orientation = Orientation.Horizontal;
                            TextBlock textblock = new TextBlock();

                            BrushConverter brush = new BrushConverter();
                            textblock.Foreground = (Brush)brush.ConvertFromString("#FF000000");
                            textblock.Text = key;
                            //TextBlock space = new TextBlock();
                            //space.Text = " : ";
                            //space.Foreground = (Brush)brush.ConvertFromString("#FF000000");
                            textblock.FontWeight = FontWeights.Bold;
                            TextBox textbox = new TextBox();
                            textbox.HorizontalAlignment = HorizontalAlignment.Left;
                            textbox.Margin = new Thickness(0, 0, 0, 0);
                            textbox.Width = 180;
                            if (!lbl_exeName.Text.Equals("Asteroids"))
                            {
                                if (exe.SettingsList != null)
                                {
                                    foreach (KeyValuePair<string, string> temp in exe.SettingsList)
                                    {
                                        if (temp.Key.Equals(key))
                                        {
                                            textbox.Text = temp.Value;
                                        }
                                    }
                                }
                                spSettings.Children.Add(textblock);
                                //spSettings.Children.Add(space);
                                spSettings.Children.Add(textbox);
                                //panel_key.Children.Add(stackpanel);
                            }
                            else
                            {
                                List<double> angle = new List<double>();
                                angle = svc.getLatestAngle(10, 1, 4, "");
                                double x = angle[0] + 5;

                                if (x > 175)
                                {
                                    x = angle[0];
                                }

                                double y = angle[1] + 5;

                                if (y < 4)
                                {
                                    y = angle[0];
                                }
                                angle.Clear();
                                if (key == "Targeted Max Angle")
                                {
                                    textbox.Text = x.ToString();
                                }
                                else if (key == "Targeted Min Angle")
                                {
                                    textbox.Text = y.ToString();
                                }
                                else
                                {
                                    textbox.Text = "300";
                                }

                                //stackpanel.Children.Add(textblock);
                                //stackpanel.Children.Add(space);
                                //stackpanel.Children.Add(textbox);
                                spSettings.Children.Add(textblock);
                                //spSettings.Children.Add(space);
                                spSettings.Children.Add(textbox);
                                //panel_key.Children.Add(stackpanel);
                            }
                        }
                    }
                    catch (Exception) { }
                }
                else
                {
                    //tohide.Visibility = Visibility.Visible;
                }

                #endregion
            }
            catch (Exception) { }

        }

        #endregion

        #region EXE List

        //private void btn_addRemove_MouseLeftButtonDown(object sender, System.Windows.Input.MouseButtonEventArgs e)
        //{
        //    string tag = ((Image)sender).Tag.ToString();
        //    if (tag.Equals("add"))
        //    {
        //        if (lbx_exe.SelectedIndex != -1)
        //        {
        //            exeItem selected = (exeItem)lbx_exe.SelectedItem;
        //            lbx_exe.Items.Remove(selected);
        //            lbx_exeAssigned.Items.Add(selected);
        //            //ServiceReference2.EXE selected = (exeItem)lbx_exe.SelectedItem;
        //            //exeRecommendedListJoint.Remove(selected);
        //            //exeAssignedListJoint.Add(selected);
        //        }
        //    }
        //    else if (tag.Equals("remove"))
        //    {
        //        if (lbx_exeAssigned.SelectedIndex != -1)
        //        {
        //            exeItem selected = (exeItem)lbx_exeAssigned.SelectedItem;
        //            lbx_exeAssigned.Items.Remove(selected);
        //            lbx_exe.Items.Add(selected);
        //            //ServiceReference2.EXE selected = (ServiceReference2.EXE)lbx_exeAssigned.SelectedItem;
        //            //exeRecommendedListJoint.Add(selected);
        //            //exeAssignedListJoint.Remove(selected);
        //        }
        //    }
        //    //lbx_exe.ItemsSource = exeRecommendedListJoint;
        //    //lbx_exeAssigned.ItemsSource = exeAssignedListJoint;
        //}

        # region Execute EXE

        private void executeProgram(ServiceReference2.EXE exe)
        {
            try
            {
                startOSK(exe.Path);
            }
            catch (Exception)
            {
                //closeOSK();
            }
        }

        System.Diagnostics.Process process;
        //static 
        bool started = false;

        public void startOSK(string path)
        {
            try
            {
                process = new System.Diagnostics.Process();
                started = true;
                //process.StartInfo = new System.Diagnostics.ProcessStartInfo((Directory.GetCurrentDirectory().Replace("\\bin\\Debug", "") + @"\osk.exe"));
                //process.StartInfo = new System.Diagnostics.ProcessStartInfo("C:\\Windows\\system32\\notepad.exe");
                //process.StartInfo = new System.Diagnostics.ProcessStartInfo("C:\\game3.exe");
                process.StartInfo = new System.Diagnostics.ProcessStartInfo(path);
                process.Start();
            }
            catch (Exception)
            {

            }

        }

        public void closeOSK()
        {
            if (started == true)
            {
                try
                {
                    process.Kill();
                    process.Dispose();
                    process = null;
                    started = false;
                }
                catch (Exception)
                {
                    started = false;
                }
            }
        }

        private void lbx_exe_MouseDoubleClick(object sender, MouseButtonEventArgs e)
        {
            #region not implemented
            //exeItem temp = (exeItem)((ListBox)sender).SelectedItem;

            //if (temp != null)
            //{

            //    if (MessageBox.Show("Execute " + temp.selectedExe.Name + " ? ", "", MessageBoxButton.YesNo) == MessageBoxResult.Yes)
            //    {
            //        List<KeyValuePair<string, string>> keyList = new List<KeyValuePair<string, string>>();
            //        keyList.Add(new KeyValuePair<string, string>("patientID", p.Uid.ToString()));
            //        for (int i = 0; i < temp.panel_key.Children.Count; i++)
            //        {
            //            try
            //            {
            //                StackPanel sp = (StackPanel)temp.panel_key.Children[i];
            //                TextBlock custkey = (TextBlock)sp.Children[0];
            //                TextBox custValue = (TextBox)sp.Children[2];
            //                KeyValuePair<string, string> key = new KeyValuePair<string, string>(custkey.Text, custValue.Text);
            //                keyList.Add(key);
            //            }
            //            catch (Exception) { }
            //        }

            //        MiddleMan.fileIO fileIO = new MiddleMan.fileIO();
            //        fileIO.write(keyList);

            //        executeProgram(((exeItem)lbx_exeAssigned.SelectedItem).selectedExe);
            //    }
            //}
            #endregion
            
        }

        //private void lbx_exe_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        //{
        //    string tag = ((ListBox)sender).Tag.ToString();

        //    switch (tag)
        //    {
        //        case ("1"):
        //            lbx_exeAssigned.SelectedItem = -1;
        //            break;
        //        case ("2"):
        //            lbx_exe.SelectedItem = -1;
        //            break;
        //    }
        //}

        # endregion

        #endregion

        //save button for treatment and joint information
        private void btn_save1_MouseLeftButtonDown(object sender, System.Windows.Input.MouseButtonEventArgs e)
        {
            #region not tested
            //List<ServiceReference2.EXE> exeTemp = new List<ServiceReference2.EXE>();
            //foreach (ServiceReference2.EXE temp in exeAssignedListJoint)
            //{
            //    exeTemp.Add(temp);
            //}

            //try
            //{
            //    List<ServiceReference2.EXE> exeList = new List<ServiceReference2.EXE>();
            //    foreach (exeItem temp in lbx_exeAssigned.Items)
            //    {
            //        List<KeyValuePair<string, string>> keyList = new List<KeyValuePair<string, string>>();
            //        for (int i = 0; i < temp.panel_key.Children.Count; i++)
            //        {
            //            try
            //            {
            //                StackPanel sp = (StackPanel)temp.panel_key.Children[i];
            //                TextBlock custkey = (TextBlock)sp.Children[0];
            //                TextBox custValue = (TextBox)sp.Children[2];
            //                KeyValuePair<string, string> key = new KeyValuePair<string, string>(custkey.Text, custValue.Text);
            //                keyList.Add(key);
            //            }
            //            catch (Exception) { }
            //        }
            //        ServiceReference2.EXE tempEXE = new ServiceReference2.EXE();
            //        tempEXE = temp.selectedExe;
            //        tempEXE.SettingsList = keyList;
            //        exeList.Add(tempEXE);
            //    }
            //    svc.createExeAssingedtoPatientCompleted += new EventHandler<ServiceReference2.createExeAssingedtoPatientCompletedEventArgs>(svc_createExeAssingedtoPatientCompleted);
            //    svc.createExeAssingedtoPatientAsync(p.Uid, exeList);

            //    //if (svc.updateProblem1(Convert.ToInt16(tbx_joint_Copy.Text), p.Uid, tbxDes.Text, Convert.ToInt16(lblSever.Text), tbxNote.Text) && svc.updateExeAssignedtoPatient(p.Uid, exeTemp, Convert.ToInt16(tbx_joint_Copy.Text)))
            //    //{
            //    //    MessageBox.Show("Update Success");
            //    //}
            //    //else
            //    //    MessageBox.Show("Error. Please try again");
            //}
            //catch (Exception)
            //{ }
            #endregion

        }

        void svc_createExeAssingedtoPatientCompleted(object sender, ServiceReference2.createExeAssingedtoPatientCompletedEventArgs e)
        {
            //if (e.Error == null && svc.updateProblem1(Convert.ToInt16(tbx_joint_Copy.Text), p.Uid, "", Convert.ToInt16(lblSever.Text), tbxNote.Text))
            //{
            //    MessageBox.Show("Update Success");
            //    try
            //    {
            //        //redownload data
            //        exeAssignedList = svc.retrieveExeAssignedtoPatient(p.Uid);
            //        patientSessionList = svc.retrieveSessionOfPatient(p.Uid);
            //        problemList = svc.retrievePatientProblems(p.Uid);
            //        createChart();
            //    }
            //    catch (Exception) { }
            //}
            //else
            //{
            //    MessageBox.Show("Error. Please try again");
            //}
        }

        private void navigationButton(object sender, System.Windows.Input.MouseButtonEventArgs e)
        {
            string clickedTag = ((TextBlock)sender).Tag.ToString();
            if (panel_kinect.Visibility == Visibility.Visible)
            {
                panel_kinect.Visibility = Visibility.Collapsed;
                currentNavigationTag = "0";
            }
            if (currentNavigationTag != clickedTag)
            {
                BrushConverter brush = new BrushConverter();
                panel_kinect.Visibility = Visibility.Collapsed;
                //stopKinect();
                //nui.Uninitialize();
                panel_treatmentAnalysis.Visibility = Visibility.Collapsed;
                panel_treatmentManager.Visibility = Visibility.Collapsed;

                btn_treatmentAnalysisB.Background = (Brush)brush.ConvertFromString("#FF373737");
                btn_treatmentManagerB.Background = (Brush)brush.ConvertFromString("#FF373737");
                btn_treatmentManager.Foreground = (Brush)brush.ConvertFromString("#FFFFFFFF");
                btn_treatmentAnalysis.Foreground = (Brush)brush.ConvertFromString("#FFFFFFFF");

                switch (clickedTag)
                {
                    case "1":
                        currentNavigationTag = clickedTag;
                        
                        btn_treatmentAnalysisB.Background = (Brush)brush.ConvertFromString("#FFFFFFFF");
                        btn_treatmentAnalysis.Foreground = (Brush)brush.ConvertFromString("#FF000000");
                        //BitmapImage test1 = new BitmapImage(new Uri("KS_treatmentManagerBG.png", UriKind.Relative));
                        //ImageBrush brush3 = new ImageBrush();
                        //brush3.ImageSource = test1;
                        //btn_treatmentAnalysisB.Background = brush3;
                        panel_treatmentAnalysis.Visibility = Visibility.Visible;
                        //panel_moreInformation_hided.Visibility = Visibility.Visible;
                        //if (selectedKeyList.Count != 0)
                        //{
                        //    PrintGridMenu.Visibility = Visibility.Visible;
                        //}
                        break;
                    case "2":
                        currentNavigationTag = clickedTag;
                        //((TextBlock)sender).Background = (Brush)brush.ConvertFromString("#FF000000");
                        //BitmapImage test2 = new BitmapImage(new Uri("KS_treatmentManagerBG.png", UriKind.Relative));
                        btn_treatmentManager.Foreground = (Brush)brush.ConvertFromString("#FF000000");
                        btn_treatmentManagerB.Background = (Brush)brush.ConvertFromString("#FFFFFFFF");
                        //ImageBrush brush2 = new ImageBrush();
                        //brush2.ImageSource = test2;
                        //btn_treatmentManagerB.Background = brush2;
                        panel_treatmentManager.Visibility = Visibility.Visible;

                        PrintGridMenu.Visibility = Visibility.Collapsed;
                        break;
                    case "10":
                        currentNavigationTag = clickedTag;
                        ((TextBlock)sender).Background = (Brush)brush.ConvertFromString("#FF000000");
                        grid_menu_show.Visibility = Visibility.Visible;
                        menuOpen = true;
                        break;
                    default:
                        break;
                }
            }

        }

        bool kinectStartedBefore = false;
        bool allowedROMtoStart = false;
        bool savingROMresult = false;
        #region old kinect
        //private void initalizeAndstartKinect()
        //{
        //    if (kinectStartedBefore == false)
        //    {
        //        try
        //        {
        //            BWstarted = true;
        //            _worker.DoWork += new DoWorkEventHandler(Worker_DoWork);
        //            CompositionTarget.Rendering += new EventHandler(CompositionTarget_Rendering);
        //            if (!xmlRead)
        //            {
        //                try
        //                {
        //                    _skeleton = new NuiUserTracker("SamplesConfig.xml");
        //                    //_skeleton = new NuiUserTracker(xmlPath());
        //                }
        //                catch (AccessViolationException)
        //                {
        //                }
        //                xmlRead = true;
        //            }


        //            //_skeleton = nuiUserTracker;
        //            //_skeleton = new NuiUserTracker("D:\\Users\\Kyzer\\Documents\\Visual Studio 2010\\Projects\\Loader\\Loader\\SamplesConfig.xml");
        //            //_skeleton.UserUpdated += new NuiUserTracker.UserUpdatedHandler(Skeleton_UserUpdated);
        //            _skeleton.UsersUpdated += new NuiUserTracker.UserListUpdatedHandler(_skeleton_UsersUpdated);
        //            //_skeleton.UserLost += new NuiUserTracker.UserUpdatedHandler(_skeleton_UserLost);
        //            //_skeleton.UserFound += new EventHandler(_skeleton_UserFound);
        //            //_skeleton.UserTracked += new NuiUserTracker.UserUpdatedHandler(_skeleton_UserTracked);
        //            _worker.WorkerSupportsCancellation = true;

        //        }
        //        catch (Exception)
        //        {
        //            stopKinect();
        //        }
        //        BWstarted = true;

        //        try
        //        {
        //            _skeleton.Start();
        //            _worker.RunWorkerAsync();

        //        }
        //        catch (Exception)
        //        {
        //            //MessageBox.Show("An error has occured. Please restart the app");
        //        }
        //        kinectStartedBefore = true;
        //    }
        //    else
        //    {
        //        startKinect();
        //    }
        //}
        #endregion
        string selectedtreatment;
        // start assessment
        //private void btn_addExecute_MouseLeftButtonDown(object sender, System.Windows.Input.MouseButtonEventArgs e)
        //{
        //    selectedtreatment = cbxTreatment.SelectedItem.ToString();
        //    if (selectedtreatment == "Fugl Meyer")
        //    {
        //        currentSessionID = 0;
        //        fuglMeyer.Visibility = Visibility.Visible;
        //        datagrid2.Visibility = Visibility.Collapsed;
        //        sp_k_startROM.Visibility = Visibility.Collapsed;
        //        #region Fugi Meyer

        //        beforetbx_joint = tbx_joint.Text;
        //        beforetbx_joint_copy = tbx_joint_Copy.Text;
        //        startShowed = false;
        //        string tag = btn_addExecute.Tag.ToString();
        //        switch (tag)
        //        {
        //            case "add":
        //                panel_calibrate.Visibility = Visibility.Visible;
        //                panel_kinect.Visibility = Visibility.Visible;
        //                skeleton.Children.Clear();
        //                maxActive = 0;
        //                maxPassive = 0;
        //                minActive = 0;
        //                minPassive = 0;
        //                sp_k_stage.Visibility = Visibility.Collapsed;
        //                sp_k_field.Visibility = Visibility.Collapsed;
        //                btn_proceed.IsEnabled = true;
        //                btn_start.IsEnabled = true;
        //                gotUser = false;
        //                sp_k_controlPanel.Visibility = Visibility.Collapsed;
        //                sp_k_controlPanel_start.Visibility = Visibility.Collapsed;
        //                lbl_k_jointName.Text = tbx_joint.Text;
        //                checkbx_passive.IsChecked = true;
        //                initalizeAndstartKinect();

        //                break;
        //            case "execute":
        //                panel_moreInformation_hided.Visibility = Visibility.Visible;
        //                panel_moreInformation_show.Visibility = Visibility.Collapsed;

        //                break;
        //            default:
        //                break;
        //        }

        //        #endregion
        //    }
        //    else if (selectedtreatment == "Joint ROM")
        //    {
        //        allowedROMtoStart = false;
        //        savingROMresult = false;
        //        startShowed = false;
        //        datagrid2.ItemsSource = null;
        //        fuglMeyer.Visibility = Visibility.Collapsed;
        //        datagrid2.Visibility = Visibility.Collapsed;
        //        panel_calibrate.Visibility = Visibility.Visible;
        //        panel_kinect.Visibility = Visibility.Visible;
        //        gotUser = false;
        //        initalizeAndstartKinect();

        //        #region resetData

        //        //maxJoint1 = 0;
        //        maxJoint2 = 0;
        //        maxJoint3 = 0;
        //        maxJoint4 = 0;
        //        maxJoint5 = 0;
        //        //maxJoint6 = 0;
        //        //maxJoint7 = 0;
        //        maxJoint8 = 0;
        //        maxJoint9 = 0;
        //        maxJoint10 = 0;
        //        maxJoint11 = 0;
        //        maxJoint12 = 0;
        //        //maxJoint13 = 0;
        //        //maxJoint14 = 0;
        //        //minJoint1 = 0;
        //        minJoint2 = 0;
        //        minJoint3 = 0;
        //        minJoint4 = 0;
        //        minJoint5 = 0;
        //        //minJoint6 = 0;
        //        //minJoint7 = 0;
        //        minJoint8 = 0;
        //        minJoint9 = 0;
        //        minJoint10 = 0;
        //        minJoint11 = 0;
        //        minJoint12 = 0;
        //        //minJoint13 = 0;
        //        //minJoint14 = 0;

        //        #endregion

        //        ds = new DataSet();
        //        dt = new DataTable();
        //        ds.Tables.Add(dt);

        //        DataColumn cl = new DataColumn("Joint", typeof(string));
        //        cl.MaxLength = 100;
        //        dt.Columns.Add(cl);

        //        cl = new DataColumn("Max Angle", typeof(string));
        //        cl.MaxLength = 100;
        //        dt.Columns.Add(cl);

        //        cl = new DataColumn("Min Angle", typeof(string));
        //        cl.MaxLength = 100;
        //        dt.Columns.Add(cl);
        //    }

        //}

        private void sp_k_startROM_MouseLeftButtonDown(object sender, System.Windows.Input.MouseButtonEventArgs e)
        {

            if (allowedROMtoStart == false)
            {
                allowedROMtoStart = true;
            }
            // TODO: Add event handler implementation here.
            datagrid2.Visibility = Visibility.Visible;
            sp_k_startROM.Visibility = Visibility.Collapsed;
        }

        #region nui.vision
        //private string status = "";
        //private int userFound = 0;
        //void _skeleton_UserTracked(object sender, NuiUserEventArgs e)
        //{
        //    if (status != "UserTracked")
        //    {
        //        Dispatcher.BeginInvoke((Action)delegate
        //        {
        //            status = "UserTracked";
        //        });
        //    }

        //}

        //void _skeleton_UserFound(object sender, EventArgs e)
        //{
        //    if (status != "UserFound")
        //    {
        //        if (userFound != 1)
        //        {
        //            Dispatcher.BeginInvoke((Action)delegate
        //            {
        //                status = "UserFound";
        //                userFound++;
        //                //lbl_k_status.Text = "User Found. Calibrate to start.";
        //            });
        //        }

        //    }                                                                                                                            
        //}

        //void _skeleton_UserLost(object sender, NuiUserEventArgs e)
        //{
        //    if (status != "UserLost")
        //    {
        //        Dispatcher.BeginInvoke((Action)delegate
        //        {
        //            status = "UserLost";
        //        });
        //    }
        //}
        #endregion
        //End assessment
        private void btn_stop_Click(object sender, RoutedEventArgs e)
        {
            border_backBG.Visibility = Visibility.Visible;
            if (selectedtreatment == "Fugl Meyer")
            {
                tbx_joint.Text = beforetbx_joint;
                tbx_joint_Copy.Text = beforetbx_joint_copy;
                panel_kinect.Visibility = Visibility.Collapsed;
                createdSession = false;
                try
                {
                    gotUser = false;
                    lbl_stage.Text = "";
                    lbl_k_jointName.Text = "";
                    //lbScore.Items.Clear();
                    //BWstarted = false;
                    lbl_k_current.Text = "0";
                    lbl_k_max.Text = "0";
                    //lbl_k_min.Text = "0";
                    lbl_k_max_passive.Text = "0";
                    lbl_k_min_passive.Text = "0";
                    max = 0;
                    min = 0;
                    maxActive = 0;
                    minActive = 0;
                    maxPassive = 0;
                    try
                    {
                        nui.Uninitialize();
                    }
                    catch (Exception)
                    {
                    }
                    //stopKinect();

                    //try
                    //{
                    //    //redownload data
                    //    patientSessionList = svc.retrieveSessionOfPatient(p.Uid);
                    //    svc.retrieveExeAssignedtoPatientCompleted += new EventHandler<ServiceReference2.retrieveExeAssignedtoPatientCompletedEventArgs>(svc_retrieveExeAssignedtoPatientCompleted);
                    //    svc.retrieveExeAssignedtoPatientAsync(p.Uid);
                    //    svc.retrievePatientProblemsCompleted += new EventHandler<ServiceReference2.retrievePatientProblemsCompletedEventArgs>(svc_retrievePatientProblemsCompleted);
                    //    svc.retrievePatientProblemsAsync(p.Uid);
                    //    setProblem(selectedProblemUID);
                    //}
                    //catch (Exception) { }
                }
                catch (Exception) { }
            }
            else if (selectedtreatment == "Joint ROM")
            {
                gotUser = false;
                panel_kinect.Visibility = Visibility.Collapsed;
                //stopKinect();
                try
                {
                    nui.Uninitialize();
                }
                catch (Exception)
                {
                }
                try
                {

                    if (savingROMresult == false)
                    {
                        savingROMresult = true;
                        if (minJoint2 != 0)
                        {
                            try
                            {
                                //save data
                                if (toSave != false)
                                {
                                    svc.createNewSessionCompleted += new EventHandler<ServiceReference2.createNewSessionCompletedEventArgs>(svc_createNewSessionCompleted);
                                    svc.createNewSessionAsync(p.Uid, 10);
                                }
                            }
                            catch (Exception) { }

                        }
                    }
                }
                catch (Exception) { }
            }
        }
        int createNewGamePlayCount = 0;
        void svc_createNewSessionCompleted(object sender, ServiceReference2.createNewSessionCompletedEventArgs e)
        {
            if (e.Error == null)
            {
                try
                {
                    int sessionID = Convert.ToInt16(e.Result);
                    createNewGamePlayCount = 0;
                    svc.createNewGamePlayCompleted += new EventHandler<ServiceReference2.createNewGamePlayCompletedEventArgs>(svc_createNewGamePlayCompleted);
                    svc.createNewGamePlayAsync(sessionID, 6, "2", "", "Max Angle Y", maxJoint2.ToString());
                    svc.createNewGamePlayAsync(sessionID, 6, "2", "", "Min Angle Y", minJoint2.ToString());
                    svc.createNewGamePlayAsync(sessionID, 6, "2", "", "Max Angle Z", maxJoint14.ToString());
                    svc.createNewGamePlayAsync(sessionID, 6, "2", "", "Min Angle Z", minJoint14.ToString());
                    svc.createNewGamePlayAsync(sessionID, 6, "2", "", "Max Angle X", maxJoint15.ToString());
                    svc.createNewGamePlayAsync(sessionID, 6, "2", "", "Min Angle X", minJoint15.ToString());

                    svc.createNewGamePlayAsync(sessionID, 8, "4", "", "Max Angle", maxJoint4.ToString());
                    svc.createNewGamePlayAsync(sessionID, 8, "4", "", "Min Angle", minJoint4.ToString());

                    svc.createNewGamePlayAsync(sessionID, 7, "3", "", "Max Angle Y", maxJoint3.ToString());
                    svc.createNewGamePlayAsync(sessionID, 7, "3", "", "Min Angle Y", minJoint3.ToString());
                    svc.createNewGamePlayAsync(sessionID, 7, "3", "", "Max Angle Z", maxJoint17.ToString());
                    svc.createNewGamePlayAsync(sessionID, 7, "3", "", "Min Angle Z", minJoint17.ToString());
                    svc.createNewGamePlayAsync(sessionID, 7, "3", "", "Max Angle X", maxJoint16.ToString());
                    svc.createNewGamePlayAsync(sessionID, 7, "3", "", "Min Angle X", minJoint16.ToString());

                    //svc.createNewGamePlayAsync(sessionID, 8, "4", "", "Max Angle", maxJoint4.ToString());
                    //svc.createNewGamePlayAsync(sessionID, 8, "4", "", "Min Angle", minJoint4.ToString());
                    svc.createNewGamePlayAsync(sessionID, 9, "5", "", "Max Angle", maxJoint5.ToString());
                    svc.createNewGamePlayAsync(sessionID, 9, "5", "", "Min Angle", minJoint5.ToString());
                    svc.createNewGamePlayAsync(sessionID, 12, "8", "", "Max Angle", maxJoint8.ToString());
                    svc.createNewGamePlayAsync(sessionID, 12, "8", "", "Min Angle", minJoint8.ToString());
                    svc.createNewGamePlayAsync(sessionID, 13, "9", "", "Max Angle X", maxJoint9.ToString());
                    svc.createNewGamePlayAsync(sessionID, 13, "9", "", "Min Angle X", minJoint9.ToString());
                    svc.createNewGamePlayAsync(sessionID, 13, "9", "", "Max Angle Z", maxJoint19.ToString());
                    svc.createNewGamePlayAsync(sessionID, 13, "9", "", "Min Angle Z", minJoint19.ToString());

                    svc.createNewGamePlayAsync(sessionID, 14, "10", "", "Max Angle X", maxJoint10.ToString());
                    svc.createNewGamePlayAsync(sessionID, 14, "10", "", "Min Angle X", minJoint10.ToString());
                    svc.createNewGamePlayAsync(sessionID, 14, "10", "", "Max Angle Z", maxJoint21.ToString());
                    svc.createNewGamePlayAsync(sessionID, 14, "10", "", "Min Angle Z", minJoint21.ToString());

                    svc.createNewGamePlayAsync(sessionID, 15, "11", "", "Max Angle", maxJoint11.ToString());
                    svc.createNewGamePlayAsync(sessionID, 15, "11", "", "Min Angle", minJoint11.ToString());
                    svc.createNewGamePlayAsync(sessionID, 16, "12", "", "Max Angle", maxJoint12.ToString());
                    svc.createNewGamePlayAsync(sessionID, 16, "12", "", "Min Angle", minJoint12.ToString());
                }
                catch (Exception) { }
            }
            else
            {
                // an error has occured. check internet
            }
        }
        bool toSave = false;
        void svc_createNewGamePlayCompleted(object sender, ServiceReference2.createNewGamePlayCompletedEventArgs e)
        {
            createNewGamePlayCount++;
            if (createNewGamePlayCount == 18)
            {
                //try
                //{
                //    //redownload data
                //    patientSessionList = svc.retrieveSessionOfPatient(p.Uid);
                //}
                //catch (Exception) { }
                //svc.retrieveExeAssignedtoPatientCompleted += new EventHandler<ServiceReference2.retrieveExeAssignedtoPatientCompletedEventArgs>(svc_retrieveExeAssignedtoPatientCompleted);
                //svc.retrieveExeAssignedtoPatientAsync(p.Uid);
                //svc.retrievePatientProblemsCompleted += new EventHandler<ServiceReference2.retrievePatientProblemsCompletedEventArgs>(svc_retrievePatientProblemsCompleted);
                //svc.retrievePatientProblemsAsync(p.Uid);

            }
        }

        # region Kinect

        #region variables
        //NuiUserTracker _skeleton;
        BackgroundWorker _worker = new BackgroundWorker();
        Color[] _userColors = { Colors.Blue, Colors.Red, Colors.Green, Colors.DarkOrange, Colors.Pink, Colors.Black };
        bool gotUser = false;
        double max = 0;
        double min = 0;
        double maxActive = 0;
        double minActive = 0;
        double maxPassive = 0;
        double minPassive = 0;
        double now = 0;
        int xmlCount = 0;
        bool startShowed = false;

        #region variables for ROM
        //double maxJoint1 = 0;
        double maxJoint2 = 0;
        double maxJoint3 = 0;
        double maxJoint4 = 0;
        double maxJoint5 = 0;
        //double maxJoint6 = 0;
        //double maxJoint7 = 0;
        double maxJoint8 = 0;
        double maxJoint9 = 0;
        double maxJoint10 = 0;
        double maxJoint11 = 0;
        double maxJoint12 = 0;
        //double maxJoint13 = 0;
        //double maxJoint14 = 0;
        //double minJoint1 = 0;
        double maxJoint14 = 0;
        double maxJoint15 = 0;
        double maxJoint16 = 0;
        double maxJoint17 = 0;
        //double maxJoint18 = 0;
        double maxJoint19 = 0;
        //double maxJoint20 = 0;
        double maxJoint21 = 0;

        double minJoint2 = 0;
        double minJoint3 = 0;
        double minJoint4 = 0;
        double minJoint5 = 0;
        //double minJoint6 = 0;
        //double minJoint7 = 0;
        double minJoint8 = 0;
        double minJoint9 = 0;
        double minJoint10 = 0;
        double minJoint11 = 0;
        double minJoint12 = 0;
        //double minJoint13 = 0;
        //double minJoint14 = 0;
        double minJoint14 = 0;
        double minJoint15 = 0;
        double minJoint16 = 0;
        double minJoint17 = 0;
        //double minJoint18 = 0;
        double minJoint19 = 0;
        //double minJoint20 = 0;
        double minJoint21 = 0;


        #endregion
        #endregion

        //void Worker_DoWork(object sender, DoWorkEventArgs e)
        //{
        //    if (BWstarted != false && _worker.CancellationPending == false)
        //    {
        //        Dispatcher.BeginInvoke((Action)delegate
        //        {
        //            if (gotUser == false)
        //            {
        //                panel_calibrate.Visibility = Visibility.Visible;
        //                gotUser = false;
        //            }
        //            else
        //            {
        //                panel_calibrate.Visibility = Visibility.Collapsed;
        //                if (startShowed == false)
        //                {
        //                    startShowed = true;
        //                    sp_k_controlPanel_start.Visibility = Visibility.Visible;
        //                }
        //            }
        //            try
        //            {

        //                //imgCamera.Source = _skeleton.RawImage;
        //                try
        //                {
        //                    //imgCamera.Source = _skeleton.RawImage;
        //                    //imgCamera.Source = _skeleton.UserTrackingImage;
        //                }
        //                catch (NullReferenceException) { }
        //            }
        //            catch (Exception)
        //            {
        //                //BWstarted = false;
        //                //if (errorShowed == false)
        //                //{
        //                //    stopKinect();
        //                //    errorShowed = true;
        //                //    if (stopping == true)
        //                //        MessageBox.Show("Please ensure that the Kinect is connected to the computer and powered on.");
        //                //}
        //            }
        //        });
        //    }
        //}

        void CompositionTarget_Rendering(object sender, EventArgs e)
        {
            if (_worker.CancellationPending)
            {
                if (BWstarted == false)
                {
                    //_worker.CancelAsync();
                    //_worker.Dispose();
                }
            }
            else
            {
                if (!_worker.IsBusy)
                {
                    _worker.RunWorkerAsync();
                }
            }
        }
        #region 3rd party sdk
        // for old sdk
        //void Skeleton_UserUpdated(object sender, NuiUserEventArgs e)
        //{

        //    //Dispatcher.BeginInvoke((Action)delegate
        //    //{
        //    //    skeleton.Children.Clear();
        //    //    if (e.Users.Count() == 0)
        //    //    {
        //    //        gotUser = false;
        //    //        panel_calibrate.Visibility = Visibility.Visible;
        //    //    }
        //    //    else
        //    //    {
        //    //        panel_calibrate.Visibility = Visibility.Collapsed;
        //    //        gotUser = true;
        //    //        if (startShowed == false)
        //    //        {
        //    //            startShowed = true;
        //    //            sp_k_controlPanel_start.Visibility = Visibility.Visible;
        //    //        }


        //    //        foreach (var user in e.Users)
        //    //        {
        //    //            Color userColor = _userColors[user.Id - 1];

        //    //            #region Get body parts coordinates

        //    //            float headX = user.Head.X;
        //    //            float headY = user.Head.Y;
        //    //            float headZ = user.Head.Z;
        //    //            if (2500 < headZ)
        //    //            {
        //    //                if (headZ < 3000)
        //    //                {
        //    //                    userColor = (Color)ColorConverter.ConvertFromString("#FFFFD700");
        //    //                }
        //    //            }
        //    //            Vector3D head3D = new Vector3D(user.Head.X, user.Head.Y, user.Head.Z);
        //    //            head3D.Normalize();

        //    //            float neckX = user.Neck.X;
        //    //            float neckY = user.Neck.Y;
        //    //            Vector3D neck3D = new Vector3D(user.Neck.X, user.Neck.Y, user.Neck.Z);
        //    //            neck3D.Normalize();

        //    //            float leftShoulderX = user.LeftShoulder.X;
        //    //            float leftShoulderY = user.LeftShoulder.Y;
        //    //            float leftShoulderZ = user.LeftShoulder.Z;
        //    //            Vector3D leftShoulder3D = new Vector3D(user.LeftShoulder.X, user.LeftShoulder.Y, user.LeftShoulder.Z);
        //    //            leftShoulder3D.Normalize();

        //    //            float leftElbowX = user.LeftElbow.X;
        //    //            float leftElbowY = user.LeftElbow.Y;
        //    //            Vector3D leftElbow3D = new Vector3D(user.LeftElbow.X, user.LeftElbow.Y, user.LeftElbow.Z);
        //    //            leftElbow3D.Normalize();

        //    //            float leftHandX = user.LeftHand.X;
        //    //            float leftHandY = user.LeftHand.Y;
        //    //            float leftHandZ = user.LeftHand.Z;
        //    //            Vector3D leftHand3D = new Vector3D(user.LeftHand.X, user.LeftHand.Y, user.LeftHand.Z);
        //    //            leftHand3D.Normalize();

        //    //            float rightShoulderX = user.RightShoulder.X;
        //    //            float rightShoulderY = user.RightShoulder.Y;
        //    //            float rightShoulderZ = user.RightShoulder.Z;
        //    //            Vector3D rightShoulder3D = new Vector3D(user.RightShoulder.X, user.RightShoulder.Y, user.RightShoulder.Z);
        //    //            rightShoulder3D.Normalize();

        //    //            float rightElbowX = user.RightElbow.X;
        //    //            float rightElbowY = user.RightElbow.Y;
        //    //            Vector3D rightElbow3D = new Vector3D(user.RightElbow.X, user.RightElbow.Y, user.RightElbow.Z);
        //    //            rightElbow3D.Normalize();

        //    //            float rightHandX = user.RightHand.X;
        //    //            float rightHandY = user.RightHand.Y;
        //    //            float rightHandZ = user.RightHand.Z;
        //    //            Vector3D rightHand3D = new Vector3D(user.RightHand.X, user.RightHand.Y, user.RightHand.Z);
        //    //            rightHand3D.Normalize();

        //    //            float waistX = user.Torso.X;
        //    //            float waistY = user.Torso.Y;
        //    //            float waistZ = user.Torso.Z;
        //    //            Vector3D waist3D = new Vector3D(user.Torso.X, user.Torso.Y, user.Torso.Z);
        //    //            waist3D.Normalize();

        //    //            float leftHipX = user.LeftHip.X;
        //    //            float leftHipY = user.LeftHip.Y;
        //    //            float leftHipZ = user.LeftHip.Z;
        //    //            Vector3D leftHip3D = new Vector3D(user.LeftHip.X, user.LeftHip.Y, user.LeftHip.Z);
        //    //            leftHip3D.Normalize();

        //    //            float leftKneeX = user.LeftKnee.X;
        //    //            float leftKneeY = user.LeftKnee.Y;
        //    //            Vector3D leftKnee3D = new Vector3D(user.LeftKnee.X, user.LeftKnee.Y, user.LeftKnee.Z);
        //    //            leftKnee3D.Normalize();

        //    //            float leftFootX = user.LeftFoot.X;
        //    //            float leftFootY = user.LeftFoot.Y;
        //    //            Vector3D leftFoot3D = new Vector3D(user.LeftFoot.X, user.LeftFoot.Y, user.LeftFoot.Z);
        //    //            leftFoot3D.Normalize();

        //    //            float rightHipX = user.RightHip.X;
        //    //            float rightHipY = user.RightHip.Y;
        //    //            float rightHipZ = user.RightHip.Z;
        //    //            Vector3D rightHip3D = new Vector3D(user.RightHip.X, user.RightHip.Y, user.RightHip.Z);
        //    //            rightHip3D.Normalize();

        //    //            float rightKneeX = user.RightKnee.X;
        //    //            float rightKneeY = user.RightKnee.Y;
        //    //            Vector3D rightKnee3D = new Vector3D(user.RightKnee.X, user.RightKnee.Y, user.RightKnee.Z);
        //    //            rightKnee3D.Normalize();


        //    //            float rightFootX = user.RightFoot.X;
        //    //            float rightFootY = user.RightFoot.Y;
        //    //            Vector3D rightFoot3D = new Vector3D(user.RightFoot.X, user.RightFoot.Y, user.RightFoot.Z);
        //    //            rightFoot3D.Normalize();
        //    //            #endregion

        //    //            //if (checkbx_active.IsChecked == true)
        //    //            //{
        //    //            //    max = Convert.ToDouble(lbl_k_max.Text);
        //    //            //    min = Convert.ToDouble(lbl_k_min.Text);
        //    //            //}
        //    //            //else
        //    //            //{
        //    //            //    max = Convert.ToDouble(lbl_k_max_passive.Text);
        //    //            //    min = Convert.ToDouble(lbl_k_min_passive.Text);
        //    //            //}

        //    //            lbl_k_jointName.Text = tbx_joint.Text;

        //    //            if (tbx_joint_Copy.Text != "")
        //    //            {

        //    //                #region calculate angle

        //    //                int joint = Convert.ToInt16(tbx_joint_Copy.Text);
        //    //                if (joint == 2)//Left Shoulders 2
        //    //                {
        //    //                    Vector3D leftShoulderV1 = leftElbow3D - leftShoulder3D;
        //    //                    Vector3D leftShoulderV2 = leftHip3D - leftShoulder3D;
        //    //                    double leftShoulderAngle = Vector3D.AngleBetween(leftShoulderV1, leftShoulderV2);
        //    //                    now = Math.Round(leftShoulderAngle, 3);

        //    //                    if (maxActive == 0 && minActive == 0)
        //    //                    {
        //    //                        if (checkbx_active.IsChecked == true)
        //    //                        {
        //    //                            maxActive = now;
        //    //                            minActive = now;
        //    //                            lowSystemTime = DateTime.Now;
        //    //                        }
        //    //                    }
        //    //                    if (maxPassive == 0 && minPassive == 0)
        //    //                    {
        //    //                        if (checkbx_passive.IsChecked == true)
        //    //                        {
        //    //                            maxPassive = now;
        //    //                            minPassive = now;
        //    //                            lowSystemTime = DateTime.Now;
        //    //                        }
        //    //                    }
        //    //                    if (checkbx_passive.IsChecked == true)
        //    //                    {

        //    //                        max = maxPassive;
        //    //                        min = minPassive;
        //    //                    }
        //    //                    else if (checkbx_active.IsChecked == true)
        //    //                    {
        //    //                        max = maxActive;
        //    //                        min = minActive;
        //    //                    }


        //    //                    if (now > max)
        //    //                    {
        //    //                        max = now;
        //    //                    }
        //    //                    else if (now < min)
        //    //                    {
        //    //                        min = now;
        //    //                    }


        //    //                    if (waistZ < leftHandZ)
        //    //                    {
        //    //                        if ((waistX - 50.0) < leftHandX)
        //    //                        {
        //    //                            if (leftHandX < (waistX + 50.0))
        //    //                            {
        //    //                                if ((waistY - 100.0) < leftHandY)
        //    //                                {
        //    //                                    if (leftHandY < (waistY + 100.0))
        //    //                                    {
        //    //                                        dif = (DateTime.Now - lowSystemTime).Seconds;
        //    //                                    }
        //    //                                }
        //    //                            }
        //    //                        }
        //    //                    }
        //    //                    else
        //    //                    { }
        //    //                }
        //    //                if (joint == 3)//Right Shoulders 3
        //    //                {
        //    //                    Vector3D rightShoulderV1 = rightElbow3D - rightShoulder3D;
        //    //                    Vector3D rightShoulderV2 = rightHip3D - rightShoulder3D;
        //    //                    double rightShoulderAngle = Vector3D.AngleBetween(rightShoulderV1, rightShoulderV2);
        //    //                    now = Math.Round(rightShoulderAngle, 3);

        //    //                    if (maxActive == 0 && minActive == 0)
        //    //                    {
        //    //                        if (checkbx_active.IsChecked == true)
        //    //                        {
        //    //                            maxActive = now;
        //    //                            minActive = now;
        //    //                            lowSystemTime = DateTime.Now;
        //    //                        }
        //    //                    }
        //    //                    if (maxPassive == 0 && minPassive == 0)
        //    //                    {
        //    //                        if (checkbx_passive.IsChecked == true)
        //    //                        {
        //    //                            maxPassive = now;
        //    //                            minPassive = now;
        //    //                            lowSystemTime = DateTime.Now;
        //    //                        }
        //    //                    }
        //    //                    if (checkbx_passive.IsChecked == true)
        //    //                    {

        //    //                        max = maxPassive;
        //    //                        min = minPassive;
        //    //                    }
        //    //                    else if (checkbx_active.IsChecked == true)
        //    //                    {
        //    //                        max = maxActive;
        //    //                        min = minActive;
        //    //                    }


        //    //                    if (now > max)
        //    //                    {
        //    //                        max = now;
        //    //                    }
        //    //                    if (now < min)
        //    //                    {
        //    //                        min = now;
        //    //                    }

        //    //                    if (waistZ < rightHandZ)
        //    //                    {
        //    //                        if ((waistX - 50.0) < rightHandX)
        //    //                        {
        //    //                            if (rightHandX < (waistX + 50.0))
        //    //                            {
        //    //                                if ((waistY - 100.0) < rightHandY)
        //    //                                {
        //    //                                    if (rightHandY < (waistY + 100.0))
        //    //                                    {
        //    //                                        dif = (DateTime.Now - lowSystemTime).Seconds;
        //    //                                    }
        //    //                                }
        //    //                            }
        //    //                        }
        //    //                    }
        //    //                    else
        //    //                    { }
        //    //                }
        //    //                else if (joint == 4)//leftElbow
        //    //                {
        //    //                    Vector3D leftElbowV1 = leftShoulder3D - leftElbow3D;
        //    //                    Vector3D leftElbowV2 = leftHand3D - leftElbow3D;
        //    //                    double leftElbowAngle = Vector3D.AngleBetween(leftElbowV1, leftElbowV2);
        //    //                    now = Math.Round(leftElbowAngle, 3);

        //    //                    if (maxActive == 0 && minActive == 0)
        //    //                    {
        //    //                        if (checkbx_active.IsChecked == true)
        //    //                        {
        //    //                            maxActive = now;
        //    //                            minActive = now;
        //    //                            lowSystemTime = DateTime.Now;
        //    //                        }
        //    //                    }
        //    //                    if (maxPassive == 0 && minPassive == 0)
        //    //                    {
        //    //                        if (checkbx_passive.IsChecked == true)
        //    //                        {
        //    //                            maxPassive = now;
        //    //                            minPassive = now;
        //    //                            lowSystemTime = DateTime.Now;
        //    //                        }
        //    //                    }
        //    //                    if (checkbx_passive.IsChecked == true)
        //    //                    {
        //    //                        max = maxPassive;
        //    //                        min = minPassive;
        //    //                    }
        //    //                    else if (checkbx_active.IsChecked == true)
        //    //                    {
        //    //                        max = maxActive;
        //    //                        min = minActive;
        //    //                    }


        //    //                    if (now > max)
        //    //                    {
        //    //                        max = now;
        //    //                    }
        //    //                    if (now < min)
        //    //                    {
        //    //                        min = now;
        //    //                    }

        //    //                    if ((headZ - 100.0) > leftHandZ)
        //    //                    {
        //    //                        if (leftHandZ < (headZ + 50))
        //    //                        {
        //    //                            if ((headX - 25.0) < leftHandX)
        //    //                            {
        //    //                                if (leftHandX < (headX + 25.0))
        //    //                                {
        //    //                                    if ((headY - 20.0) < leftHandY)
        //    //                                    {
        //    //                                        if (leftHandY < (headY + 20.0))
        //    //                                        {

        //    //                                            dif = (DateTime.Now - lowSystemTime).Seconds;

        //    //                                        }
        //    //                                    }
        //    //                                }
        //    //                            }
        //    //                        }
        //    //                    }

        //    //                }
        //    //                else if (joint == 5)//rightElbow
        //    //                {
        //    //                    Vector3D rightElbowV1 = rightShoulder3D - rightElbow3D;
        //    //                    Vector3D rightElbowV2 = rightHand3D - rightElbow3D;
        //    //                    double rightElbowAngle = Vector3D.AngleBetween(rightElbowV1, rightElbowV2);
        //    //                    now = Math.Round(rightElbowAngle, 3);

        //    //                    if (maxActive == 0 && minActive == 0)
        //    //                    {
        //    //                        if (checkbx_active.IsChecked == true)
        //    //                        {
        //    //                            maxActive = now;
        //    //                            minActive = now;
        //    //                            lowSystemTime = DateTime.Now;
        //    //                        }
        //    //                    }
        //    //                    if (maxPassive == 0 && minPassive == 0)
        //    //                    {
        //    //                        if (checkbx_passive.IsChecked == true)
        //    //                        {
        //    //                            maxPassive = now;
        //    //                            minPassive = now;
        //    //                            lowSystemTime = DateTime.Now;
        //    //                        }
        //    //                    }
        //    //                    if (checkbx_passive.IsChecked == true)
        //    //                    {

        //    //                        max = maxPassive;
        //    //                        min = minPassive;
        //    //                    }
        //    //                    else if (checkbx_active.IsChecked == true)
        //    //                    {
        //    //                        max = maxActive;
        //    //                        min = minActive;
        //    //                    }


        //    //                    if (now > max)
        //    //                    {
        //    //                        max = now;
        //    //                    }
        //    //                    if (now < min)
        //    //                    {
        //    //                        min = now;
        //    //                    }

        //    //                    if ((headZ - 100.0) > rightHandZ)
        //    //                    {
        //    //                        if (rightHandZ < (headZ + 50))
        //    //                        {
        //    //                            if ((headX - 20.0) < rightHandX)
        //    //                            {
        //    //                                if (rightHandX < (headX + 20.0))
        //    //                                {
        //    //                                    if ((headY - 20.0) < rightHandY)
        //    //                                    {
        //    //                                        if (rightHandY < (headY + 20.0))
        //    //                                        {
        //    //                                            dif = (DateTime.Now - lowSystemTime).Seconds;
        //    //                                        }
        //    //                                    }
        //    //                                }
        //    //                            }
        //    //                        }
        //    //                    }
        //    //                }
        //    //                else if (joint == 6)//Torso
        //    //                {
        //    //                    Vector3D spine = waist3D - neck3D;
        //    //                    Vector3D leftShoulder = leftShoulder3D - neck3D;
        //    //                    double Torso = Vector3D.AngleBetween(spine, leftShoulder);
        //    //                    now = Math.Round(Torso, 3);

        //    //                    if (maxActive == 0 && minActive == 0)
        //    //                    {
        //    //                        if (checkbx_active.IsChecked == true)
        //    //                        {
        //    //                            maxActive = now;
        //    //                            minActive = now;
        //    //                            lowSystemTime = DateTime.Now;
        //    //                        }
        //    //                    }
        //    //                    if (maxPassive == 0 && minPassive == 0)
        //    //                    {
        //    //                        if (checkbx_passive.IsChecked == true)
        //    //                        {
        //    //                            maxPassive = now;
        //    //                            minPassive = now;
        //    //                            lowSystemTime = DateTime.Now;
        //    //                        }
        //    //                    }
        //    //                    if (checkbx_passive.IsChecked == true)
        //    //                    {

        //    //                        max = maxPassive;
        //    //                        min = minPassive;
        //    //                    }
        //    //                    else if (checkbx_active.IsChecked == true)
        //    //                    {
        //    //                        max = maxActive;
        //    //                        min = minActive;
        //    //                    }


        //    //                    if (now > max)
        //    //                    {
        //    //                        max = now;
        //    //                    }
        //    //                    if (now < min)
        //    //                    {
        //    //                        min = now;
        //    //                    }

        //    //                }
        //    //                else if (joint == 9)//Left hips 9 
        //    //                {
        //    //                    Vector3D leftHipV1 = rightKnee3D - leftHip3D;
        //    //                    Vector3D leftHipV2 = leftKnee3D - leftHip3D;
        //    //                    double leftHipAngle = Vector3D.AngleBetween(leftHipV1, leftHipV2);
        //    //                    now = Math.Round(leftHipAngle, 3);

        //    //                    if (maxActive == 0 && minActive == 0)
        //    //                    {
        //    //                        if (checkbx_active.IsChecked == true)
        //    //                        {
        //    //                            maxActive = now;
        //    //                            minActive = now;
        //    //                            lowSystemTime = DateTime.Now;
        //    //                        }
        //    //                    }
        //    //                    if (maxPassive == 0 && minPassive == 0)
        //    //                    {
        //    //                        if (checkbx_passive.IsChecked == true)
        //    //                        {
        //    //                            maxPassive = now;
        //    //                            minPassive = now;
        //    //                            lowSystemTime = DateTime.Now;
        //    //                        }
        //    //                    }
        //    //                    if (checkbx_passive.IsChecked == true)
        //    //                    {

        //    //                        max = maxPassive;
        //    //                        min = minPassive;
        //    //                    }
        //    //                    else if (checkbx_active.IsChecked == true)
        //    //                    {
        //    //                        max = maxActive;
        //    //                        min = minActive;
        //    //                    }


        //    //                    if (now > max)
        //    //                    {
        //    //                        max = now;
        //    //                        dif = (DateTime.Now - lowSystemTime).Seconds;
        //    //                    }
        //    //                    if (now < min)
        //    //                    {
        //    //                        min = now;
        //    //                    }

        //    //                }
        //    //                else if (joint == 10)//Right hips 10 
        //    //                {
        //    //                    Vector3D rightHipV1 = leftKnee3D - rightHip3D;
        //    //                    Vector3D rightHipV2 = rightKnee3D - rightHip3D;
        //    //                    double rightHipAngle = Vector3D.AngleBetween(rightHipV1, rightHipV2);
        //    //                    now = Math.Round(rightHipAngle, 3);

        //    //                    if (maxActive == 0 && minActive == 0)
        //    //                    {
        //    //                        if (checkbx_active.IsChecked == true)
        //    //                        {
        //    //                            maxActive = now;
        //    //                            minActive = now;
        //    //                            lowSystemTime = DateTime.Now;
        //    //                        }
        //    //                    }
        //    //                    if (maxPassive == 0 && minPassive == 0)
        //    //                    {
        //    //                        if (checkbx_passive.IsChecked == true)
        //    //                        {
        //    //                            maxPassive = now;
        //    //                            minPassive = now;
        //    //                            lowSystemTime = DateTime.Now;
        //    //                        }
        //    //                    }
        //    //                    if (checkbx_passive.IsChecked == true)
        //    //                    {

        //    //                        max = maxPassive;
        //    //                        min = minPassive;
        //    //                    }
        //    //                    else if (checkbx_active.IsChecked == true)
        //    //                    {
        //    //                        max = maxActive;
        //    //                        min = minActive;
        //    //                    }


        //    //                    if (now > max)
        //    //                    {
        //    //                        max = now;
        //    //                        dif = (DateTime.Now - lowSystemTime).Seconds;
        //    //                    }
        //    //                    if (now < min)
        //    //                    {
        //    //                        min = now;
        //    //                    }

        //    //                }
        //    //                else if (joint == 11)//leftknee
        //    //                {
        //    //                    Vector3D leftKneeV1 = leftHip3D - leftKnee3D;
        //    //                    Vector3D leftKneeV2 = leftFoot3D - leftKnee3D;
        //    //                    double leftKneeAngle = Vector3D.AngleBetween(leftKneeV1, leftKneeV2);
        //    //                    now = Math.Round(leftKneeAngle, 3);

        //    //                    if (maxActive == 0 && minActive == 0)
        //    //                    {
        //    //                        if (checkbx_active.IsChecked == true)
        //    //                        {
        //    //                            maxActive = now;
        //    //                            minActive = now;
        //    //                            lowSystemTime = DateTime.Now;
        //    //                        }
        //    //                    }
        //    //                    if (maxPassive == 0 && minPassive == 0)
        //    //                    {
        //    //                        if (checkbx_passive.IsChecked == true)
        //    //                        {
        //    //                            maxPassive = now;
        //    //                            minPassive = now;
        //    //                            lowSystemTime = DateTime.Now;
        //    //                        }
        //    //                    }
        //    //                    if (checkbx_passive.IsChecked == true)
        //    //                    {

        //    //                        max = maxPassive;
        //    //                        min = minPassive;
        //    //                    }
        //    //                    else if (checkbx_active.IsChecked == true)
        //    //                    {
        //    //                        max = maxActive;
        //    //                        min = minActive;
        //    //                    }


        //    //                    if (now > max)
        //    //                    {
        //    //                        max = now;
        //    //                    }
        //    //                    if (now < min)
        //    //                    {
        //    //                        min = now;
        //    //                        dif = (DateTime.Now - lowSystemTime).Seconds;
        //    //                    }


        //    //                }
        //    //                else if (joint == 12)//rightknee
        //    //                {
        //    //                    Vector3D rightKneeV1 = rightHip3D - rightKnee3D;
        //    //                    Vector3D rightKneeV2 = rightFoot3D - rightKnee3D;
        //    //                    double rightKneeAngle = Vector3D.AngleBetween(rightKneeV1, rightKneeV2);
        //    //                    now = Math.Round(rightKneeAngle, 3);

        //    //                    if (maxActive == 0 && minActive == 0)
        //    //                    {
        //    //                        if (checkbx_active.IsChecked == true)
        //    //                        {
        //    //                            maxActive = now;
        //    //                            minActive = now;
        //    //                            lowSystemTime = DateTime.Now;
        //    //                        }
        //    //                    }
        //    //                    if (maxPassive == 0 && minPassive == 0)
        //    //                    {
        //    //                        if (checkbx_passive.IsChecked == true)
        //    //                        {
        //    //                            maxPassive = now;
        //    //                            minPassive = now;
        //    //                            lowSystemTime = DateTime.Now;
        //    //                        }
        //    //                    }
        //    //                    if (checkbx_passive.IsChecked == true)
        //    //                    {

        //    //                        max = maxPassive;
        //    //                        min = minPassive;
        //    //                    }
        //    //                    else if (checkbx_active.IsChecked == true)
        //    //                    {
        //    //                        max = maxActive;
        //    //                        min = minActive;
        //    //                    }


        //    //                    if (now > max)
        //    //                    {
        //    //                        max = now;
        //    //                    }
        //    //                    if (now < min)
        //    //                    {
        //    //                        min = now;
        //    //                    }

        //    //                }

        //    //                if (now.IsNaN() || max.IsNaN() || min.IsNaN())
        //    //                {
        //    //                    try
        //    //                    {
        //    //                     
        //    //                        stopKinect();
        //    //                        startKinect();

        //    //                        _worker.RunWorkerAsync();
        //    //                    }
        //    //                    catch (Exception) { }
        //    //                }
        //    //                else
        //    //                {
        //    //                    max = Math.Round(max, 1);
        //    //                    min = Math.Round(min, 1);
        //    //                    lbl_k_current.Text = now.ToString();
        //    //                    //string maxstring = (max - min).ToString();
        //    //                    if (checkbx_active.IsChecked == true)
        //    //                    {
        //    //                        maxActive = max;
        //    //                        minActive = min;
        //    //                        lbl_k_max.Text = max.ToString();
        //    //                        lbl_k_min.Text = min.ToString();

        //    //                        //lbl_k_min.Visibility = Visibility.Visible;
        //    //                        //lbl_k_min_passive.Visibility = Visibility.Collapsed;
        //    //                    }
        //    //                    else
        //    //                    {
        //    //                        minPassive = min;
        //    //                        maxPassive = max;
        //    //                        lbl_k_max_passive.Text = max.ToString();
        //    //                        lbl_k_min_passive.Text = min.ToString();

        //    //                        //lbl_k_min_passive.Visibility = Visibility.Visible;
        //    //                        //lbl_k_min.Visibility = Visibility.Collapsed;
        //    //                    }

        //    //                }
        //    //                #endregion

        //    //                #region Draw skeleton points
        //    //                if (headX != 0 && headY != 0)
        //    //                {
        //    //                    DrawCircle(headX, headY, userColor);
        //    //                    DrawCircle(neckX, neckY, userColor);
        //    //                    DrawCircle(leftShoulderX, leftShoulderY, userColor);
        //    //                    DrawCircle(leftElbowX, leftElbowY, userColor);
        //    //                    DrawCircle(leftHandX, leftHandY, userColor);
        //    //                    DrawCircle(waistX, waistY, userColor);
        //    //                    DrawCircle(rightShoulderX, rightShoulderY, userColor);
        //    //                    DrawCircle(rightElbowX, rightElbowY, userColor);
        //    //                    DrawCircle(rightHandX, rightHandY, userColor);
        //    //                    DrawCircle(leftHipX, leftHipY, userColor);
        //    //                    DrawCircle(leftKneeX, leftKneeY, userColor);
        //    //                    DrawCircle(leftFootX, leftFootY, userColor);
        //    //                    DrawCircle(rightHipX, rightHipY, userColor);
        //    //                    DrawCircle(rightKneeX, rightKneeY, userColor);
        //    //                    DrawCircle(rightFootX, rightFootY, userColor);
        //    //                    gotUser = true;
        //    //                }
        //    //                else
        //    //                {
        //    //                    gotUser = false;
        //    //                    try
        //    //                    {

        //    //                        if (xmlRead)
        //    //                        {
        //    //                            _skeleton.StopUserTracking();
        //    //                            _skeleton.Stop();
        //    //                            try
        //    //                            {
        //    //                                _skeleton = null;
        //    //                                _skeleton = new NuiUserTracker("");
        //    //                            }
        //    //                            catch (Exception) { }
        //    //                            xmlRead = false;
        //    //                        }


        //    //                        if (!xmlRead)
        //    //                        {
        //    //                            try
        //    //                            {
        //    //                                _skeleton = new NuiUserTracker("SamplesConfig.xml");
        //    //                            }
        //    //                            catch (Exception) { }
        //    //                            xmlRead = true;
        //    //                            _skeleton.Start();
        //    //                        }


        //    //                    }
        //    //                    catch (Exception) { }
        //    //                }


        //    //                #endregion
        //    //            }
        //    //        }
        //    //    }
        //    //});

        //}
        DataTable dt;
        DataSet ds;
        //void _skeleton_UsersUpdated(object sender, NuiUserListEventArgs e)
        //{
        //    Dispatcher.BeginInvoke((Action)delegate
        //    {
        //        //skeleton.Children.Clear();

        //        if (e.Users.Count() == 0)
        //        {
        //            gotUser = false;
        //            panel_calibrate.Visibility = Visibility.Visible;
        //        }
        //        else
        //        {
        //            gotUser = true;
        //            panel_calibrate.Visibility = Visibility.Collapsed;
        //        }
        //    });

        //    if (selectedtreatment == "Fugl Meyer")
        //    {
        //        #region Fugl Meyer
        //        Dispatcher.BeginInvoke((Action)delegate
        //        {
        //            if (startShowed == false)
        //            {
        //                startShowed = true;
        //                sp_k_controlPanel_start.Visibility = Visibility.Visible;
        //            }


        //            foreach (var user in e.Users)
        //            {
        //                Color userColor = _userColors[user.Id - 1];

        //                #region Get body parts coordinates

        //                float headX = user.Head.X;
        //                float headY = user.Head.Y;
        //                float headZ = user.Head.Z;
        //                if (2500 < headZ)
        //                {
        //                    if (headZ < 3000)
        //                    {
        //                        userColor = (Color)ColorConverter.ConvertFromString("#FFFFD700");
        //                    }
        //                }
        //                Vector3D head3D = new Vector3D(user.Head.X, user.Head.Y, user.Head.Z);
        //                head3D.Normalize();

        //                float neckX = user.Neck.X;
        //                float neckY = user.Neck.Y;
        //                Vector3D neck3D = new Vector3D(user.Neck.X, user.Neck.Y, user.Neck.Z);
        //                neck3D.Normalize();

        //                float leftShoulderX = user.LeftShoulder.X;
        //                float leftShoulderY = user.LeftShoulder.Y;
        //                float leftShoulderZ = user.LeftShoulder.Z;
        //                Vector3D leftShoulder3D = new Vector3D(user.LeftShoulder.X, user.LeftShoulder.Y, user.LeftShoulder.Z);
        //                leftShoulder3D.Normalize();

        //                float leftElbowX = user.LeftElbow.X;
        //                float leftElbowY = user.LeftElbow.Y;
        //                Vector3D leftElbow3D = new Vector3D(user.LeftElbow.X, user.LeftElbow.Y, user.LeftElbow.Z);
        //                leftElbow3D.Normalize();

        //                float leftHandX = user.LeftHand.X;
        //                float leftHandY = user.LeftHand.Y;
        //                float leftHandZ = user.LeftHand.Z;
        //                Vector3D leftHand3D = new Vector3D(user.LeftHand.X, user.LeftHand.Y, user.LeftHand.Z);
        //                leftHand3D.Normalize();

        //                float rightShoulderX = user.RightShoulder.X;
        //                float rightShoulderY = user.RightShoulder.Y;
        //                float rightShoulderZ = user.RightShoulder.Z;
        //                Vector3D rightShoulder3D = new Vector3D(user.RightShoulder.X, user.RightShoulder.Y, user.RightShoulder.Z);
        //                rightShoulder3D.Normalize();

        //                float rightElbowX = user.RightElbow.X;
        //                float rightElbowY = user.RightElbow.Y;
        //                Vector3D rightElbow3D = new Vector3D(user.RightElbow.X, user.RightElbow.Y, user.RightElbow.Z);
        //                rightElbow3D.Normalize();

        //                float rightHandX = user.RightHand.X;
        //                float rightHandY = user.RightHand.Y;
        //                float rightHandZ = user.RightHand.Z;
        //                Vector3D rightHand3D = new Vector3D(user.RightHand.X, user.RightHand.Y, user.RightHand.Z);
        //                rightHand3D.Normalize();

        //                float waistX = user.Torso.X;
        //                float waistY = user.Torso.Y;
        //                float waistZ = user.Torso.Z;
        //                Vector3D waist3D = new Vector3D(user.Torso.X, user.Torso.Y, user.Torso.Z);
        //                waist3D.Normalize();

        //                float leftHipX = user.LeftHip.X;
        //                float leftHipY = user.LeftHip.Y;
        //                float leftHipZ = user.LeftHip.Z;
        //                Vector3D leftHip3D = new Vector3D(user.LeftHip.X, user.LeftHip.Y, user.LeftHip.Z);
        //                leftHip3D.Normalize();

        //                float leftKneeX = user.LeftKnee.X;
        //                float leftKneeY = user.LeftKnee.Y;
        //                Vector3D leftKnee3D = new Vector3D(user.LeftKnee.X, user.LeftKnee.Y, user.LeftKnee.Z);
        //                leftKnee3D.Normalize();

        //                float leftFootX = user.LeftFoot.X;
        //                float leftFootY = user.LeftFoot.Y;
        //                Vector3D leftFoot3D = new Vector3D(user.LeftFoot.X, user.LeftFoot.Y, user.LeftFoot.Z);
        //                leftFoot3D.Normalize();

        //                float rightHipX = user.RightHip.X;
        //                float rightHipY = user.RightHip.Y;
        //                float rightHipZ = user.RightHip.Z;
        //                Vector3D rightHip3D = new Vector3D(user.RightHip.X, user.RightHip.Y, user.RightHip.Z);
        //                rightHip3D.Normalize();

        //                float rightKneeX = user.RightKnee.X;
        //                float rightKneeY = user.RightKnee.Y;
        //                Vector3D rightKnee3D = new Vector3D(user.RightKnee.X, user.RightKnee.Y, user.RightKnee.Z);
        //                rightKnee3D.Normalize();


        //                float rightFootX = user.RightFoot.X;
        //                float rightFootY = user.RightFoot.Y;
        //                Vector3D rightFoot3D = new Vector3D(user.RightFoot.X, user.RightFoot.Y, user.RightFoot.Z);
        //                rightFoot3D.Normalize();
        //                #endregion

        //                lbl_k_jointName.Text = tbx_joint.Text;
        //                tbx_joint_Copy.Text = "2";
        //                if (tbx_joint_Copy.Text != "")
        //                {
        //                    //if (allowedROMtoStart == true)
        //                    //{
        //                    #region calculate angle

        //                    int joint = Convert.ToInt16(tbx_joint_Copy.Text);
        //                    if (joint == 2)//Left Shoulders 2
        //                    {
        //                        Vector3D leftShoulderV1 = leftElbow3D - leftShoulder3D;
        //                        Vector3D leftShoulderV2 = leftHip3D - leftShoulder3D;
        //                        double leftShoulderAngle = Vector3D.AngleBetween(leftShoulderV1, leftShoulderV2);
        //                        now = Math.Round(leftShoulderAngle, 3);

        //                        if (maxActive == 0 && minActive == 0)
        //                        {
        //                            if (checkbx_active.IsChecked == true)
        //                            {
        //                                maxActive = now;
        //                                minActive = now;
        //                                lowSystemTime = DateTime.Now;
        //                            }
        //                        }
        //                        if (maxPassive == 0 && minPassive == 0)
        //                        {
        //                            if (checkbx_passive.IsChecked == true)
        //                            {
        //                                maxPassive = now;
        //                                minPassive = now;
        //                                lowSystemTime = DateTime.Now;
        //                            }
        //                        }
        //                        if (checkbx_passive.IsChecked == true)
        //                        {

        //                            max = maxPassive;
        //                            min = minPassive;
        //                        }
        //                        else if (checkbx_active.IsChecked == true)
        //                        {
        //                            max = maxActive;
        //                            min = minActive;
        //                        }


        //                        if (now > max)
        //                        {
        //                            max = now;
        //                        }
        //                        else if (now < min)
        //                        {
        //                            min = now;
        //                        }


        //                        if (waistZ < leftHandZ)
        //                        {
        //                            if ((waistX - 50.0) < leftHandX)
        //                            {
        //                                if (leftHandX < (waistX + 50.0))
        //                                {
        //                                    if ((waistY - 100.0) < leftHandY)
        //                                    {
        //                                        if (leftHandY < (waistY + 100.0))
        //                                        {
        //                                            dif = (DateTime.Now - lowSystemTime).Seconds;
        //                                        }
        //                                    }
        //                                }
        //                            }
        //                        }
        //                        else
        //                        { }
        //                    }
        //                    if (joint == 3)//Right Shoulders 3
        //                    {
        //                        Vector3D rightShoulderV1 = rightElbow3D - rightShoulder3D;
        //                        Vector3D rightShoulderV2 = rightHip3D - rightShoulder3D;
        //                        double rightShoulderAngle = Vector3D.AngleBetween(rightShoulderV1, rightShoulderV2);
        //                        now = Math.Round(rightShoulderAngle, 3);

        //                        if (maxActive == 0 && minActive == 0)
        //                        {
        //                            if (checkbx_active.IsChecked == true)
        //                            {
        //                                maxActive = now;
        //                                minActive = now;
        //                                lowSystemTime = DateTime.Now;
        //                            }
        //                        }
        //                        if (maxPassive == 0 && minPassive == 0)
        //                        {
        //                            if (checkbx_passive.IsChecked == true)
        //                            {
        //                                maxPassive = now;
        //                                minPassive = now;
        //                                lowSystemTime = DateTime.Now;
        //                            }
        //                        }
        //                        if (checkbx_passive.IsChecked == true)
        //                        {

        //                            max = maxPassive;
        //                            min = minPassive;
        //                        }
        //                        else if (checkbx_active.IsChecked == true)
        //                        {
        //                            max = maxActive;
        //                            min = minActive;
        //                        }


        //                        if (now > max)
        //                        {
        //                            max = now;
        //                        }
        //                        if (now < min)
        //                        {
        //                            min = now;
        //                        }

        //                        if (waistZ < rightHandZ)
        //                        {
        //                            if ((waistX - 50.0) < rightHandX)
        //                            {
        //                                if (rightHandX < (waistX + 50.0))
        //                                {
        //                                    if ((waistY - 100.0) < rightHandY)
        //                                    {
        //                                        if (rightHandY < (waistY + 100.0))
        //                                        {
        //                                            dif = (DateTime.Now - lowSystemTime).Seconds;
        //                                        }
        //                                    }
        //                                }
        //                            }
        //                        }
        //                        else
        //                        { }
        //                    }
        //                    else if (joint == 4)//leftElbow
        //                    {
        //                        Vector3D leftElbowV1 = leftShoulder3D - leftElbow3D;
        //                        Vector3D leftElbowV2 = leftHand3D - leftElbow3D;
        //                        double leftElbowAngle = Vector3D.AngleBetween(leftElbowV1, leftElbowV2);
        //                        now = Math.Round(leftElbowAngle, 3);

        //                        if (maxActive == 0 && minActive == 0)
        //                        {
        //                            if (checkbx_active.IsChecked == true)
        //                            {
        //                                maxActive = now;
        //                                minActive = now;
        //                                lowSystemTime = DateTime.Now;
        //                            }
        //                        }
        //                        if (maxPassive == 0 && minPassive == 0)
        //                        {
        //                            if (checkbx_passive.IsChecked == true)
        //                            {
        //                                maxPassive = now;
        //                                minPassive = now;
        //                                lowSystemTime = DateTime.Now;
        //                            }
        //                        }
        //                        if (checkbx_passive.IsChecked == true)
        //                        {
        //                            max = maxPassive;
        //                            min = minPassive;
        //                        }
        //                        else if (checkbx_active.IsChecked == true)
        //                        {
        //                            max = maxActive;
        //                            min = minActive;
        //                        }


        //                        if (now > max)
        //                        {
        //                            max = now;
        //                        }
        //                        if (now < min)
        //                        {
        //                            min = now;
        //                        }

        //                        if ((headZ - 100.0) > leftHandZ)
        //                        {
        //                            if (leftHandZ < (headZ + 50))
        //                            {
        //                                if ((headX - 25.0) < leftHandX)
        //                                {
        //                                    if (leftHandX < (headX + 25.0))
        //                                    {
        //                                        if ((headY - 20.0) < leftHandY)
        //                                        {
        //                                            if (leftHandY < (headY + 20.0))
        //                                            {

        //                                                dif = (DateTime.Now - lowSystemTime).Seconds;

        //                                            }
        //                                        }
        //                                    }
        //                                }
        //                            }
        //                        }

        //                    }
        //                    else if (joint == 5)//rightElbow
        //                    {
        //                        Vector3D rightElbowV1 = rightShoulder3D - rightElbow3D;
        //                        Vector3D rightElbowV2 = rightHand3D - rightElbow3D;
        //                        double rightElbowAngle = Vector3D.AngleBetween(rightElbowV1, rightElbowV2);
        //                        now = Math.Round(rightElbowAngle, 3);

        //                        if (maxActive == 0 && minActive == 0)
        //                        {
        //                            if (checkbx_active.IsChecked == true)
        //                            {
        //                                maxActive = now;
        //                                minActive = now;
        //                                lowSystemTime = DateTime.Now;
        //                            }
        //                        }
        //                        if (maxPassive == 0 && minPassive == 0)
        //                        {
        //                            if (checkbx_passive.IsChecked == true)
        //                            {
        //                                maxPassive = now;
        //                                minPassive = now;
        //                                lowSystemTime = DateTime.Now;
        //                            }
        //                        }
        //                        if (checkbx_passive.IsChecked == true)
        //                        {

        //                            max = maxPassive;
        //                            min = minPassive;
        //                        }
        //                        else if (checkbx_active.IsChecked == true)
        //                        {
        //                            max = maxActive;
        //                            min = minActive;
        //                        }


        //                        if (now > max)
        //                        {
        //                            max = now;
        //                        }
        //                        if (now < min)
        //                        {
        //                            min = now;
        //                        }

        //                        if ((headZ - 100.0) > rightHandZ)
        //                        {
        //                            if (rightHandZ < (headZ + 50))
        //                            {
        //                                if ((headX - 20.0) < rightHandX)
        //                                {
        //                                    if (rightHandX < (headX + 20.0))
        //                                    {
        //                                        if ((headY - 20.0) < rightHandY)
        //                                        {
        //                                            if (rightHandY < (headY + 20.0))
        //                                            {
        //                                                dif = (DateTime.Now - lowSystemTime).Seconds;
        //                                            }
        //                                        }
        //                                    }
        //                                }
        //                            }
        //                        }
        //                    }
        //                    else if (joint == 8)//Torso
        //                    {
        //                        Vector3D spine = waist3D - neck3D;
        //                        Vector3D leftShoulder = leftShoulder3D - neck3D;
        //                        double Torso = Vector3D.AngleBetween(spine, leftShoulder);
        //                        now = Math.Round(Torso, 3);

        //                        if (maxActive == 0 && minActive == 0)
        //                        {
        //                            if (checkbx_active.IsChecked == true)
        //                            {
        //                                maxActive = now;
        //                                minActive = now;
        //                                lowSystemTime = DateTime.Now;
        //                            }
        //                        }
        //                        if (maxPassive == 0 && minPassive == 0)
        //                        {
        //                            if (checkbx_passive.IsChecked == true)
        //                            {
        //                                maxPassive = now;
        //                                minPassive = now;
        //                                lowSystemTime = DateTime.Now;
        //                            }
        //                        }
        //                        if (checkbx_passive.IsChecked == true)
        //                        {

        //                            max = maxPassive;
        //                            min = minPassive;
        //                        }
        //                        else if (checkbx_active.IsChecked == true)
        //                        {
        //                            max = maxActive;
        //                            min = minActive;
        //                        }


        //                        if (now > max)
        //                        {
        //                            max = now;
        //                        }
        //                        if (now < min)
        //                        {
        //                            min = now;
        //                        }

        //                    }
        //                    else if (joint == 9)//Left hips 9 
        //                    {
        //                        Vector3D leftHipV1 = rightKnee3D - leftHip3D;
        //                        Vector3D leftHipV2 = leftKnee3D - leftHip3D;
        //                        double leftHipAngle = Vector3D.AngleBetween(leftHipV1, leftHipV2);
        //                        now = Math.Round(leftHipAngle, 3);

        //                        if (maxActive == 0 && minActive == 0)
        //                        {
        //                            if (checkbx_active.IsChecked == true)
        //                            {
        //                                maxActive = now;
        //                                minActive = now;
        //                                lowSystemTime = DateTime.Now;
        //                            }
        //                        }
        //                        if (maxPassive == 0 && minPassive == 0)
        //                        {
        //                            if (checkbx_passive.IsChecked == true)
        //                            {
        //                                maxPassive = now;
        //                                minPassive = now;
        //                                lowSystemTime = DateTime.Now;
        //                            }
        //                        }
        //                        if (checkbx_passive.IsChecked == true)
        //                        {

        //                            max = maxPassive;
        //                            min = minPassive;
        //                        }
        //                        else if (checkbx_active.IsChecked == true)
        //                        {
        //                            max = maxActive;
        //                            min = minActive;
        //                        }


        //                        if (now > max)
        //                        {
        //                            max = now;
        //                            dif = (DateTime.Now - lowSystemTime).Seconds;
        //                        }
        //                        if (now < min)
        //                        {
        //                            min = now;
        //                        }

        //                    }
        //                    else if (joint == 10)//Right hips 10 
        //                    {
        //                        Vector3D rightHipV1 = leftKnee3D - rightHip3D;
        //                        Vector3D rightHipV2 = rightKnee3D - rightHip3D;
        //                        double rightHipAngle = Vector3D.AngleBetween(rightHipV1, rightHipV2);
        //                        now = Math.Round(rightHipAngle, 3);

        //                        if (maxActive == 0 && minActive == 0)
        //                        {
        //                            if (checkbx_active.IsChecked == true)
        //                            {
        //                                maxActive = now;
        //                                minActive = now;
        //                                lowSystemTime = DateTime.Now;
        //                            }
        //                        }
        //                        if (maxPassive == 0 && minPassive == 0)
        //                        {
        //                            if (checkbx_passive.IsChecked == true)
        //                            {
        //                                maxPassive = now;
        //                                minPassive = now;
        //                                lowSystemTime = DateTime.Now;
        //                            }
        //                        }
        //                        if (checkbx_passive.IsChecked == true)
        //                        {

        //                            max = maxPassive;
        //                            min = minPassive;
        //                        }
        //                        else if (checkbx_active.IsChecked == true)
        //                        {
        //                            max = maxActive;
        //                            min = minActive;
        //                        }


        //                        if (now > max)
        //                        {
        //                            max = now;
        //                            dif = (DateTime.Now - lowSystemTime).Seconds;
        //                        }
        //                        if (now < min)
        //                        {
        //                            min = now;
        //                        }

        //                    }
        //                    else if (joint == 11)//leftknee
        //                    {
        //                        Vector3D leftKneeV1 = leftHip3D - leftKnee3D;
        //                        Vector3D leftKneeV2 = leftFoot3D - leftKnee3D;
        //                        double leftKneeAngle = Vector3D.AngleBetween(leftKneeV1, leftKneeV2);
        //                        now = Math.Round(leftKneeAngle, 3);

        //                        if (maxActive == 0 && minActive == 0)
        //                        {
        //                            if (checkbx_active.IsChecked == true)
        //                            {
        //                                maxActive = now;
        //                                minActive = now;
        //                                lowSystemTime = DateTime.Now;
        //                            }
        //                        }
        //                        if (maxPassive == 0 && minPassive == 0)
        //                        {
        //                            if (checkbx_passive.IsChecked == true)
        //                            {
        //                                maxPassive = now;
        //                                minPassive = now;
        //                                lowSystemTime = DateTime.Now;
        //                            }
        //                        }
        //                        if (checkbx_passive.IsChecked == true)
        //                        {

        //                            max = maxPassive;
        //                            min = minPassive;
        //                        }
        //                        else if (checkbx_active.IsChecked == true)
        //                        {
        //                            max = maxActive;
        //                            min = minActive;
        //                        }


        //                        if (now > max)
        //                        {
        //                            max = now;
        //                        }
        //                        if (now < min)
        //                        {
        //                            min = now;
        //                            dif = (DateTime.Now - lowSystemTime).Seconds;
        //                        }


        //                    }
        //                    else if (joint == 12)//rightknee
        //                    {
        //                        Vector3D rightKneeV1 = rightHip3D - rightKnee3D;
        //                        Vector3D rightKneeV2 = rightFoot3D - rightKnee3D;
        //                        double rightKneeAngle = Vector3D.AngleBetween(rightKneeV1, rightKneeV2);
        //                        now = Math.Round(rightKneeAngle, 3);

        //                        if (maxActive == 0 && minActive == 0)
        //                        {
        //                            if (checkbx_active.IsChecked == true)
        //                            {
        //                                maxActive = now;
        //                                minActive = now;
        //                                lowSystemTime = DateTime.Now;
        //                            }
        //                        }
        //                        if (maxPassive == 0 && minPassive == 0)
        //                        {
        //                            if (checkbx_passive.IsChecked == true)
        //                            {
        //                                maxPassive = now;
        //                                minPassive = now;
        //                                lowSystemTime = DateTime.Now;
        //                            }
        //                        }
        //                        if (checkbx_passive.IsChecked == true)
        //                        {

        //                            max = maxPassive;
        //                            min = minPassive;
        //                        }
        //                        else if (checkbx_active.IsChecked == true)
        //                        {
        //                            max = maxActive;
        //                            min = minActive;
        //                        }


        //                        if (now > max)
        //                        {
        //                            max = now;
        //                        }
        //                        if (now < min)
        //                        {
        //                            min = now;
        //                        }

        //                    }

        //                    if (now.IsNaN() || max.IsNaN() || min.IsNaN())
        //                    {
        //                        try
        //                        {

        //                            stopKinect();
        //                            startKinect();

        //                            _worker.RunWorkerAsync();
        //                        }
        //                        catch (Exception) { }
        //                    }
        //                    else
        //                    {
        //                        max = Math.Round(max, 1);
        //                        min = Math.Round(min, 1);
        //                        lbl_k_current.Text = now.ToString();
        //                        //string maxstring = (max - min).ToString();
        //                        if (checkbx_active.IsChecked == true)
        //                        {
        //                            maxActive = max;
        //                            minActive = min;
        //                            lbl_k_max.Text = max.ToString();
        //                            lbl_k_min.Text = min.ToString();

        //                            //lbl_k_min.Visibility = Visibility.Visible;
        //                            //lbl_k_min_passive.Visibility = Visibility.Collapsed;
        //                        }
        //                        else
        //                        {
        //                            minPassive = min;
        //                            maxPassive = max;
        //                            lbl_k_max_passive.Text = max.ToString();
        //                            lbl_k_min_passive.Text = min.ToString();

        //                            //lbl_k_min_passive.Visibility = Visibility.Visible;
        //                            //lbl_k_min.Visibility = Visibility.Collapsed;
        //                        }

        //                    }
        //                    #endregion
        //                    //}
        //                    //#region Draw skeleton points
        //                    //if (headX != 0 && headY != 0)
        //                    //{
        //                    //    #region DrawLine for joints
        //                    //    Line myNeck = new Line();
        //                    //    myNeck.Stroke = Brushes.Black;
        //                    //    myNeck.X1 = Convert.ToDouble(headX + 15);
        //                    //    myNeck.Y1 = Convert.ToDouble(headY + 15);
        //                    //    myNeck.X2 = Convert.ToDouble(neckX + 15);
        //                    //    myNeck.Y2 = Convert.ToDouble(neckY + 15);
        //                    //    myNeck.StrokeThickness = 5;
        //                    //    //skeleton.Children.Add(myNeck);

        //                    //    Line myRightUpperLimbLower = new Line();
        //                    //    myRightUpperLimbLower.Stroke = Brushes.Black;
        //                    //    myRightUpperLimbLower.X1 = Convert.ToDouble(rightElbowX + 15);
        //                    //    myRightUpperLimbLower.Y1 = Convert.ToDouble(rightElbowY + 15);
        //                    //    myRightUpperLimbLower.X2 = Convert.ToDouble(rightHandX + 15);
        //                    //    myRightUpperLimbLower.Y2 = Convert.ToDouble(rightHandY + 15);
        //                    //    myRightUpperLimbLower.StrokeThickness = 5;
        //                    //    //skeleton.Children.Add(myRightUpperLimbLower);

        //                    //    Line myRightUpperLimbUpper = new Line();
        //                    //    myRightUpperLimbUpper.Stroke = Brushes.Black;
        //                    //    myRightUpperLimbUpper.X1 = Convert.ToDouble(rightElbowX + 15);
        //                    //    myRightUpperLimbUpper.Y1 = Convert.ToDouble(rightElbowY + 15);
        //                    //    myRightUpperLimbUpper.X2 = Convert.ToDouble(rightShoulderX + 15);
        //                    //    myRightUpperLimbUpper.Y2 = Convert.ToDouble(rightShoulderY + 15);
        //                    //    myRightUpperLimbUpper.StrokeThickness = 5;
        //                    //    //skeleton.Children.Add(myRightUpperLimbUpper);

        //                    //    Line myRightShoulder = new Line();
        //                    //    myRightShoulder.Stroke = Brushes.Black;
        //                    //    myRightShoulder.X1 = Convert.ToDouble(neckX + 15);
        //                    //    myRightShoulder.Y1 = Convert.ToDouble(neckY + 15);
        //                    //    myRightShoulder.X2 = Convert.ToDouble(rightShoulderX + 15);
        //                    //    myRightShoulder.Y2 = Convert.ToDouble(rightShoulderY + 15);
        //                    //    myRightShoulder.StrokeThickness = 5;
        //                    //    //skeleton.Children.Add(myRightShoulder);

        //                    //    Line myLeftUpperLimbLower = new Line();
        //                    //    myLeftUpperLimbLower.Stroke = Brushes.Black;
        //                    //    myLeftUpperLimbLower.X1 = Convert.ToDouble(leftElbowX + 15);
        //                    //    myLeftUpperLimbLower.Y1 = Convert.ToDouble(leftElbowY + 15);
        //                    //    myLeftUpperLimbLower.X2 = Convert.ToDouble(leftHandX + 15);
        //                    //    myLeftUpperLimbLower.Y2 = Convert.ToDouble(leftHandY + 15);
        //                    //    myLeftUpperLimbLower.StrokeThickness = 5;
        //                    //    skeleton.Children.Add(myLeftUpperLimbLower);

        //                    //    Line myLeftUpperLimbUpper = new Line();
        //                    //    myLeftUpperLimbUpper.Stroke = Brushes.Black;
        //                    //    myLeftUpperLimbUpper.X1 = Convert.ToDouble(leftElbowX + 15);
        //                    //    myLeftUpperLimbUpper.Y1 = Convert.ToDouble(leftElbowY + 15);
        //                    //    myLeftUpperLimbUpper.X2 = Convert.ToDouble(leftShoulderX + 15);
        //                    //    myLeftUpperLimbUpper.Y2 = Convert.ToDouble(leftShoulderY + 15);
        //                    //    myLeftUpperLimbUpper.StrokeThickness = 5;
        //                    //    skeleton.Children.Add(myLeftUpperLimbUpper);

        //                    //    Line myLeftShoulder = new Line();
        //                    //    myLeftShoulder.Stroke = Brushes.Black;
        //                    //    myLeftShoulder.X1 = Convert.ToDouble(neckX + 15);
        //                    //    myLeftShoulder.Y1 = Convert.ToDouble(neckY + 15);
        //                    //    myLeftShoulder.X2 = Convert.ToDouble(leftShoulderX + 15);
        //                    //    myLeftShoulder.Y2 = Convert.ToDouble(leftShoulderY + 15);
        //                    //    myLeftShoulder.StrokeThickness = 5;
        //                    //    skeleton.Children.Add(myLeftShoulder);

        //                    //    //Legs
        //                    //    Line myLeftLowerLimbLower = new Line();
        //                    //    myLeftLowerLimbLower.Stroke = Brushes.Black;
        //                    //    myLeftLowerLimbLower.X1 = Convert.ToDouble(leftFootX + 15);
        //                    //    myLeftLowerLimbLower.Y1 = Convert.ToDouble(leftFootY + 15);
        //                    //    myLeftLowerLimbLower.X2 = Convert.ToDouble(leftKneeX + 15);
        //                    //    myLeftLowerLimbLower.Y2 = Convert.ToDouble(leftKneeY + 15);
        //                    //    myLeftLowerLimbLower.StrokeThickness = 5;
        //                    //    skeleton.Children.Add(myLeftLowerLimbLower);

        //                    //    Line myLeftLowerLimbUpper = new Line();
        //                    //    myLeftLowerLimbUpper.Stroke = Brushes.Black;
        //                    //    myLeftLowerLimbUpper.X1 = Convert.ToDouble(leftKneeX + 15);
        //                    //    myLeftLowerLimbUpper.Y1 = Convert.ToDouble(leftKneeY + 15);
        //                    //    myLeftLowerLimbUpper.X2 = Convert.ToDouble(leftHipX + 15);
        //                    //    myLeftLowerLimbUpper.Y2 = Convert.ToDouble(leftHipY + 15);
        //                    //    myLeftLowerLimbUpper.StrokeThickness = 5;
        //                    //    skeleton.Children.Add(myLeftLowerLimbUpper);

        //                    //    Line myRightLowerLimbLower = new Line();
        //                    //    myRightLowerLimbLower.Stroke = Brushes.Black;
        //                    //    myRightLowerLimbLower.X1 = Convert.ToDouble(rightFootX + 15);
        //                    //    myRightLowerLimbLower.Y1 = Convert.ToDouble(rightFootY + 15);
        //                    //    myRightLowerLimbLower.X2 = Convert.ToDouble(rightKneeX + 15);
        //                    //    myRightLowerLimbLower.Y2 = Convert.ToDouble(rightKneeY + 15);
        //                    //    myRightLowerLimbLower.StrokeThickness = 5;
        //                    //    skeleton.Children.Add(myRightLowerLimbLower);

        //                    //    Line myRightLowerLimbUpper = new Line();
        //                    //    myRightLowerLimbUpper.Stroke = Brushes.Black;
        //                    //    myRightLowerLimbUpper.X1 = Convert.ToDouble(rightKneeX + 15);
        //                    //    myRightLowerLimbUpper.Y1 = Convert.ToDouble(rightKneeY + 15);
        //                    //    myRightLowerLimbUpper.X2 = Convert.ToDouble(rightHipX + 15);
        //                    //    myRightLowerLimbUpper.Y2 = Convert.ToDouble(rightHipY + 15);
        //                    //    myRightLowerLimbUpper.StrokeThickness = 5;
        //                    //    skeleton.Children.Add(myRightLowerLimbUpper);

        //                    //    Line myLeftLowerWrist = new Line();
        //                    //    myLeftLowerWrist.Stroke = Brushes.Black;
        //                    //    myLeftLowerWrist.X1 = Convert.ToDouble(waistX + 15);
        //                    //    myLeftLowerWrist.Y1 = Convert.ToDouble(waistY + 15);
        //                    //    myLeftLowerWrist.X2 = Convert.ToDouble(leftHipX + 15);
        //                    //    myLeftLowerWrist.Y2 = Convert.ToDouble(leftHipY + 15);
        //                    //    myLeftLowerWrist.StrokeThickness = 5;
        //                    //    skeleton.Children.Add(myLeftLowerWrist);

        //                    //    Line myRightLowerWrist = new Line();
        //                    //    myRightLowerWrist.Stroke = Brushes.Black;
        //                    //    myRightLowerWrist.X1 = Convert.ToDouble(waistX + 15);
        //                    //    myRightLowerWrist.Y1 = Convert.ToDouble(waistY + 15);
        //                    //    myRightLowerWrist.X2 = Convert.ToDouble(rightHipX + 15);
        //                    //    myRightLowerWrist.Y2 = Convert.ToDouble(rightHipY + 15);
        //                    //    myRightLowerWrist.StrokeThickness = 5;
        //                    //    skeleton.Children.Add(myRightLowerWrist);

        //                    //    Line myLeftUpperWrist = new Line();
        //                    //    myLeftUpperWrist.Stroke = Brushes.Black;
        //                    //    myLeftUpperWrist.X1 = Convert.ToDouble(waistX + 15);
        //                    //    myLeftUpperWrist.Y1 = Convert.ToDouble(waistY + 15);
        //                    //    myLeftUpperWrist.X2 = Convert.ToDouble(leftShoulderX + 15);
        //                    //    myLeftUpperWrist.Y2 = Convert.ToDouble(leftShoulderY + 15);
        //                    //    myLeftUpperWrist.StrokeThickness = 5;
        //                    //    skeleton.Children.Add(myLeftUpperWrist);

        //                    //    Line myRightUpperWrist = new Line();
        //                    //    myRightUpperWrist.Stroke = Brushes.Black;
        //                    //    myRightUpperWrist.X1 = Convert.ToDouble(waistX + 15);
        //                    //    myRightUpperWrist.Y1 = Convert.ToDouble(waistY + 15);
        //                    //    myRightUpperWrist.X2 = Convert.ToDouble(rightShoulderX + 15);
        //                    //    myRightUpperWrist.Y2 = Convert.ToDouble(rightShoulderY + 15);
        //                    //    myRightUpperWrist.StrokeThickness = 5;
        //                    //    skeleton.Children.Add(myRightUpperWrist);
        //                    //    #endregion

        //                    //    #region DrawCircle for each point
        //                    //    DrawCircle(headX, headY, userColor);
        //                    //    //DrawCircle(neckX, neckY, userColor);
        //                    //    //DrawCircle(leftShoulderX, leftShoulderY, userColor);
        //                    //    //DrawCircle(leftElbowX, leftElbowY, userColor);
        //                    //    //DrawCircle(leftHandX, leftHandY, userColor);
        //                    //    //DrawCircle(waistX, waistY, userColor);
        //                    //    //DrawCircle(rightShoulderX, rightShoulderY, userColor);
        //                    //    //DrawCircle(rightElbowX, rightElbowY, userColor);
        //                    //    //DrawCircle(rightHandX, rightHandY, userColor);
        //                    //    //DrawCircle(leftHipX, leftHipY, userColor);
        //                    //    //DrawCircle(leftKneeX, leftKneeY, userColor);
        //                    //    //DrawCircle(leftFootX, leftFootY, userColor);
        //                    //    //DrawCircle(rightHipX, rightHipY, userColor);
        //                    //    //DrawCircle(rightKneeX, rightKneeY, userColor);
        //                    //    //DrawCircle(rightFootX, rightFootY, userColor);
        //                    //    gotUser = true;
        //                    //    #endregion
        //                    //}
        //                    //else
        //                    //{
        //                    //    stopKinect();
        //                    //    startKinect();
        //                    //}
        //                    //#endregion
        //                    //#region Draw skeleton points
        //                    //if (headX != 0 && headY != 0)
        //                    //{
        //                    //    #region DrawCircle for each point
        //                    //    DrawCircle(headX, headY, userColor);
        //                    //    DrawCircle(neckX, neckY, userColor);
        //                    //    DrawCircle(leftShoulderX, leftShoulderY, userColor);
        //                    //    DrawCircle(leftElbowX, leftElbowY, userColor);
        //                    //    DrawCircle(leftHandX, leftHandY, userColor);
        //                    //    DrawCircle(waistX, waistY, userColor);
        //                    //    DrawCircle(rightShoulderX, rightShoulderY, userColor);
        //                    //    DrawCircle(rightElbowX, rightElbowY, userColor);
        //                    //    DrawCircle(rightHandX, rightHandY, userColor);
        //                    //    DrawCircle(leftHipX, leftHipY, userColor);
        //                    //    DrawCircle(leftKneeX, leftKneeY, userColor);
        //                    //    DrawCircle(leftFootX, leftFootY, userColor);
        //                    //    DrawCircle(rightHipX, rightHipY, userColor);
        //                    //    DrawCircle(rightKneeX, rightKneeY, userColor);
        //                    //    DrawCircle(rightFootX, rightFootY, userColor);
        //                    //    gotUser = true;
        //                    //    #endregion
        //                    //}
        //                    //else
        //                    //{
        //                    //    stopKinect();
        //                    //    startKinect();
        //                    //}
        //                    //#endregion
        //                }


        //            }
        //        });
        //        #endregion
        //    }
        //    else if (selectedtreatment == "Joint ROM")
        //    {
        //        //#region Joint ROM
        //        //Dispatcher.BeginInvoke((Action)delegate
        //        //{
        //        //    if (startShowed == false)
        //        //    {
        //        //        startShowed = true;
        //        //        sp_k_startROM.Visibility = Visibility.Visible;
        //        //    }

        //        //    foreach (var user in e.Users)
        //        //    {
        //        //        Color userColor = _userColors[user.Id - 1];

        //        //        #region Get body parts coordinates

        //        //        float headX = user.Head.X;
        //        //        float headY = user.Head.Y;
        //        //        float headZ = user.Head.Z;
        //        //        if (2500 < headZ)
        //        //        {
        //        //            if (headZ < 3000)
        //        //            {
        //        //                userColor = (Color)ColorConverter.ConvertFromString("#FFFFD700");
        //        //            }
        //        //        }
        //        //        Vector3D head3D = new Vector3D(user.Head.X, user.Head.Y, user.Head.Z);
        //        //        head3D.Normalize();

        //        //        float neckX = user.Neck.X;
        //        //        float neckY = user.Neck.Y;
        //        //        Vector3D neck3D = new Vector3D(user.Neck.X, user.Neck.Y, user.Neck.Z);
        //        //        neck3D.Normalize();

        //        //        float leftShoulderX = user.LeftShoulder.X;
        //        //        float leftShoulderY = user.LeftShoulder.Y;
        //        //        float leftShoulderZ = user.LeftShoulder.Z;
        //        //        Vector3D leftShoulder3D = new Vector3D(user.LeftShoulder.X, user.LeftShoulder.Y, user.LeftShoulder.Z);
        //        //        leftShoulder3D.Normalize();

        //        //        float leftElbowX = user.LeftElbow.X;
        //        //        float leftElbowY = user.LeftElbow.Y;
        //        //        Vector3D leftElbow3D = new Vector3D(user.LeftElbow.X, user.LeftElbow.Y, user.LeftElbow.Z);
        //        //        leftElbow3D.Normalize();

        //        //        float leftHandX = user.LeftHand.X;
        //        //        float leftHandY = user.LeftHand.Y;
        //        //        float leftHandZ = user.LeftHand.Z;
        //        //        Vector3D leftHand3D = new Vector3D(user.LeftHand.X, user.LeftHand.Y, user.LeftHand.Z);
        //        //        leftHand3D.Normalize();

        //        //        float rightShoulderX = user.RightShoulder.X;
        //        //        float rightShoulderY = user.RightShoulder.Y;
        //        //        float rightShoulderZ = user.RightShoulder.Z;
        //        //        Vector3D rightShoulder3D = new Vector3D(user.RightShoulder.X, user.RightShoulder.Y, user.RightShoulder.Z);
        //        //        rightShoulder3D.Normalize();
        //        //        #region invis arm
        //        //        float fakeRightShoulderX = user.RightShoulder.X;
        //        //        float fakeRightShoulderY = user.RightShoulder.Y;
        //        //        float fakeRightShoulderZ = user.RightShoulder.Z - 0.5f;
        //        //        Vector3D fakeRightShoulder3D = new Vector3D(user.RightShoulder.X, user.RightShoulder.Y, user.RightShoulder.Z - 0.5f);
        //        //        fakeRightShoulder3D.Normalize();

        //        //        float fakeRightShoulderXAxis3 = user.RightShoulder.X + 0.5f;
        //        //        float fakeRightShoulderYAxis3 = user.RightShoulder.Y;
        //        //        float fakeRightShoulderZAxis3 = user.RightShoulder.Z;
        //        //        Vector3D fakeRightShoulder3DAxis3 = new Vector3D(user.RightShoulder.X + 0.5f, user.RightShoulder.Y, user.RightShoulder.Z);
        //        //        fakeRightShoulder3DAxis3.Normalize();

        //        //        float fakeLeftShoulderX = user.LeftShoulder.X;
        //        //        float fakeLeftShoulderY = user.LeftShoulder.Y;
        //        //        float fakeLeftShoulderZ = user.LeftShoulder.Z - 0.5f;
        //        //        Vector3D fakeLeftShoulder3D = new Vector3D(user.LeftShoulder.X, user.LeftShoulder.Y, user.LeftShoulder.Z - 0.5f);
        //        //        fakeLeftShoulder3D.Normalize();

        //        //        float fakeLeftShoulderXAxis3 = user.LeftShoulder.X - 0.5f;
        //        //        float fakeLeftShoulderYAxis3 = user.LeftShoulder.Y;
        //        //        float fakeLeftShoulderZAxis3 = user.LeftShoulder.Z;
        //        //        Vector3D fakeLeftShoulder3DAxis3 = new Vector3D(user.LeftShoulder.X - 0.5f, user.LeftShoulder.Y, user.LeftShoulder.Z);
        //        //        fakeLeftShoulder3DAxis3.Normalize();

        //        //        #endregion

        //        //        float frightHandX = user.RightShoulder.X;
        //        //        float frightHandY = user.RightShoulder.Y;
        //        //        float frightHandZ = user.RightShoulder.Z + 5;
        //        //        Vector3D frightHand3D = new Vector3D(user.RightShoulder.X, user.RightShoulder.Y, user.RightShoulder.Z + 5);
        //        //        frightHand3D.Normalize();

        //        //        float rightElbowX = user.RightElbow.X;
        //        //        float rightElbowY = user.RightElbow.Y;
        //        //        Vector3D rightElbow3D = new Vector3D(user.RightElbow.X, user.RightElbow.Y, user.RightElbow.Z);
        //        //        rightElbow3D.Normalize();

        //        //        float rightHandX = user.RightHand.X;
        //        //        float rightHandY = user.RightHand.Y;
        //        //        float rightHandZ = user.RightHand.Z;
        //        //        Vector3D rightHand3D = new Vector3D(user.RightHand.X, user.RightHand.Y, user.RightHand.Z);
        //        //        rightHand3D.Normalize();

        //        //        float waistX = user.Torso.X;
        //        //        float waistY = user.Torso.Y;
        //        //        float waistZ = user.Torso.Z;
        //        //        Vector3D waist3D = new Vector3D(user.Torso.X, user.Torso.Y, user.Torso.Z);
        //        //        waist3D.Normalize();

        //        //        float leftHipX = user.LeftHip.X;
        //        //        float leftHipY = user.LeftHip.Y;
        //        //        float leftHipZ = user.LeftHip.Z;
        //        //        Vector3D leftHip3D = new Vector3D(user.LeftHip.X, user.LeftHip.Y, user.LeftHip.Z);
        //        //        leftHip3D.Normalize();

        //        //        float leftKneeX = user.LeftKnee.X;
        //        //        float leftKneeY = user.LeftKnee.Y;
        //        //        Vector3D leftKnee3D = new Vector3D(user.LeftKnee.X, user.LeftKnee.Y, user.LeftKnee.Z);
        //        //        leftKnee3D.Normalize();

        //        //        float leftFootX = user.LeftFoot.X;
        //        //        float leftFootY = user.LeftFoot.Y;
        //        //        Vector3D leftFoot3D = new Vector3D(user.LeftFoot.X, user.LeftFoot.Y, user.LeftFoot.Z);
        //        //        leftFoot3D.Normalize();

        //        //        float rightHipX = user.RightHip.X;
        //        //        float rightHipY = user.RightHip.Y;
        //        //        float rightHipZ = user.RightHip.Z;
        //        //        Vector3D rightHip3D = new Vector3D(user.RightHip.X, user.RightHip.Y, user.RightHip.Z);
        //        //        rightHip3D.Normalize();
        //        //        #region invis hip
        //        //        float fakeRightHipX = user.RightHip.X;
        //        //        float fakeRightHipY = user.RightHip.Y;
        //        //        float fakeRightHipZ = user.RightHip.Z - 0.5f;
        //        //        Vector3D fakeRightHipX3D = new Vector3D(user.RightHip.X, user.RightHip.Y, user.RightHip.Z - 0.5f);
        //        //        fakeRightHipX3D.Normalize();

        //        //        float fakeRightHipXAxis3 = user.RightHip.X + 0.5f;
        //        //        float fakeRightHipYAxis3 = user.RightHip.Y;
        //        //        float fakeRightHipZAxis3 = user.RightHip.Z;
        //        //        Vector3D fakeRightHipX3DAxis3 = new Vector3D(user.RightHip.X + 0.5f, user.RightHip.Y, user.RightHip.Z);
        //        //        fakeRightHipX3DAxis3.Normalize();

        //        //        float fakeLeftHipX = user.LeftHip.X;
        //        //        float fakeLeftHipY = user.LeftHip.Y;
        //        //        float fakeLeftHipZ = user.LeftHip.Z - 0.5f;
        //        //        Vector3D fakeLeftHipX3D = new Vector3D(user.LeftHip.X, user.LeftHip.Y, user.LeftHip.Z - 0.5f);
        //        //        fakeLeftHipX3D.Normalize();

        //        //        float fakeLeftHipXAxis3 = user.LeftHip.X + 0.5f;
        //        //        float fakeLeftHipYAxis3 = user.LeftHip.Y;
        //        //        float fakeLeftHipZAxis3 = user.LeftHip.Z;
        //        //        Vector3D fakeLeftHipX3DAxis3 = new Vector3D(user.LeftHip.X + 0.5f, user.LeftHip.Y, user.LeftHip.Z);
        //        //        fakeLeftHipX3DAxis3.Normalize();
        //        //        #endregion

        //        //        float rightKneeX = user.RightKnee.X;
        //        //        float rightKneeY = user.RightKnee.Y;
        //        //        Vector3D rightKnee3D = new Vector3D(user.RightKnee.X, user.RightKnee.Y, user.RightKnee.Z);
        //        //        rightKnee3D.Normalize();


        //        //        float rightFootX = user.RightFoot.X;
        //        //        float rightFootY = user.RightFoot.Y;
        //        //        Vector3D rightFoot3D = new Vector3D(user.RightFoot.X, user.RightFoot.Y, user.RightFoot.Z);
        //        //        rightFoot3D.Normalize();
        //        //        #endregion

        //        //        dt.Rows.Clear();
        //        //        if (allowedROMtoStart == true)
        //        //        {
        //        //            #region calculate angle
        //        //            #region LeftShoulder X
        //        //            Vector3D leftShoulderV1Axis3 = leftElbow3D - leftShoulder3D;
        //        //            Vector3D leftShoulderV2Axis3 = fakeLeftShoulder3DAxis3 - leftShoulder3D;
        //        //            double leftShoulderAngleAxis3 = Vector3D.AngleBetween(leftShoulderV1Axis3, leftShoulderV2Axis3);
        //        //            now = Math.Round(leftShoulderAngleAxis3, 3);
        //        //            if (!now.IsNaN())
        //        //            {
        //        //                switch (maxJoint15 == 0 && minJoint15 == 0)
        //        //                {
        //        //                    case true:
        //        //                        maxJoint15 = now;
        //        //                        minJoint15 = now;
        //        //                        break;
        //        //                }

        //        //                switch (now > maxJoint15)
        //        //                {
        //        //                    case true:
        //        //                        maxJoint15 = now;
        //        //                        break;
        //        //                }
        //        //                switch (now < minJoint15)
        //        //                {
        //        //                    case true:
        //        //                        minJoint15 = now;
        //        //                        break;
        //        //                }

        //        //                DataRow rw = dt.NewRow();
        //        //                dt.Rows.Add(rw);
        //        //                rw["Joint"] = "Left Shoulder X";
        //        //                rw["Max Angle"] = maxJoint15.ToString();
        //        //                rw["Min Angle"] = minJoint15.ToString();

        //        //            }
        //        //            #endregion
        //        //            #region Left Shoulders Y

        //        //            Vector3D leftShoulderV1 = leftElbow3D - leftShoulder3D;
        //        //            Vector3D leftShoulderV2 = leftHip3D - leftShoulder3D;
        //        //            double leftShoulderAngle = Vector3D.AngleBetween(leftShoulderV1, leftShoulderV2);
        //        //            now = Math.Round(leftShoulderAngle, 3);
        //        //            if (!now.IsNaN())
        //        //            {
        //        //                switch (maxJoint2 == 0 && minJoint2 == 0)
        //        //                {
        //        //                    case true:
        //        //                        maxJoint2 = now;
        //        //                        minJoint2 = now;
        //        //                        break;
        //        //                }

        //        //                switch (now > maxJoint2)
        //        //                {
        //        //                    case true:
        //        //                        maxJoint2 = now;
        //        //                        break;
        //        //                }
        //        //                switch (now < minJoint2)
        //        //                {
        //        //                    case true:
        //        //                        minJoint2 = now;
        //        //                        break;
        //        //                }

        //        //                DataRow rw = dt.NewRow();
        //        //                dt.Rows.Add(rw);
        //        //                rw["Joint"] = "Left Shoulder Y";
        //        //                rw["Max Angle"] = maxJoint2.ToString();
        //        //                rw["Min Angle"] = minJoint2.ToString(); ;
        //        //            }


        //        //            #endregion
        //        //            #region LeftShoulder Z
        //        //            Vector3D leftShoulderV1Axis2 = leftElbow3D - leftShoulder3D;
        //        //            Vector3D leftShoulderV2Axis2 = fakeLeftShoulder3D - leftShoulder3D;
        //        //            double leftShoulderAngleAxis2 = Vector3D.AngleBetween(leftShoulderV1Axis2, leftShoulderV2Axis2);
        //        //            now = Math.Round(leftShoulderAngleAxis2, 3);
        //        //            if (!now.IsNaN())
        //        //            {
        //        //                switch (maxJoint14 == 0 && minJoint14 == 0)
        //        //                {
        //        //                    case true:
        //        //                        maxJoint14 = now;
        //        //                        minJoint14 = now;
        //        //                        break;
        //        //                }

        //        //                switch (now > maxJoint14)
        //        //                {
        //        //                    case true:
        //        //                        maxJoint14 = now;
        //        //                        break;
        //        //                }
        //        //                switch (now < minJoint14)
        //        //                {
        //        //                    case true:
        //        //                        minJoint14 = now;
        //        //                        break;
        //        //                }

        //        //                DataRow rw = dt.NewRow();
        //        //                dt.Rows.Add(rw);
        //        //                rw["Joint"] = "Left Shoulder Z";
        //        //                rw["Max Angle"] = maxJoint14.ToString();
        //        //                rw["Min Angle"] = minJoint14.ToString();

        //        //            }
        //        //            #endregion

        //        //            #region Right Shoulder X
        //        //            Vector3D rightShoulderV1Axis2 = rightElbow3D - rightShoulder3D;
        //        //            Vector3D rightShoulderV2Axis2 = fakeRightShoulder3D - rightShoulder3D;
        //        //            double rightShoulderAngleAxis2 = Vector3D.AngleBetween(rightShoulderV1Axis2, rightShoulderV2Axis2);
        //        //            now = Math.Round(rightShoulderAngleAxis2, 3);
        //        //            if (!now.IsNaN())
        //        //            {
        //        //                switch (maxJoint16 == 0 && minJoint16 == 0)
        //        //                {
        //        //                    case true:
        //        //                        maxJoint16 = now;
        //        //                        minJoint16 = now;
        //        //                        break;

        //        //                }

        //        //                switch (now > maxJoint16)
        //        //                {
        //        //                    case true:
        //        //                        maxJoint16 = now;
        //        //                        break;
        //        //                }
        //        //                switch (now < minJoint16)
        //        //                {
        //        //                    case true:
        //        //                        minJoint16 = now;
        //        //                        break;
        //        //                }

        //        //                DataRow rw = dt.NewRow();
        //        //                dt.Rows.Add(rw);
        //        //                rw["Joint"] = "Right Shoulder X";
        //        //                rw["Max Angle"] = maxJoint16.ToString();
        //        //                rw["Min Angle"] = minJoint16.ToString();
        //        //            }
        //        //            #endregion
        //        //            #region Right Shoulders Y

        //        //            Vector3D rightShoulderV1 = rightElbow3D - rightShoulder3D;
        //        //            Vector3D rightShoulderV2 = rightHip3D - rightShoulder3D;
        //        //            double rightShoulderAngle = Vector3D.AngleBetween(rightShoulderV1, rightShoulderV2);
        //        //            now = Math.Round(rightShoulderAngle, 3);
        //        //            if (!now.IsNaN())
        //        //            {
        //        //                switch (maxJoint3 == 0 && minJoint3 == 0)
        //        //                {
        //        //                    case true:
        //        //                        maxJoint3 = now;
        //        //                        minJoint3 = now;
        //        //                        break;
        //        //                }

        //        //                switch (now > maxJoint3)
        //        //                {
        //        //                    case true:
        //        //                        maxJoint3 = now;
        //        //                        break;
        //        //                }
        //        //                switch (now < minJoint3)
        //        //                {
        //        //                    case true:
        //        //                        minJoint3 = now;
        //        //                        break;
        //        //                }

        //        //                DataRow rw1 = dt.NewRow();
        //        //                dt.Rows.Add(rw1);
        //        //                rw1["Joint"] = "Right Shoulder Y";
        //        //                rw1["Max Angle"] = maxJoint3.ToString();
        //        //                rw1["Min Angle"] = minJoint3.ToString(); ;
        //        //            }
        //        //            #endregion                            
        //        //            #region Right Shoulder Z
        //        //            Vector3D rightShoulderV1Axis3 = rightElbow3D - rightShoulder3D;
        //        //            Vector3D rightShoulderV2Axis3 = fakeRightShoulder3DAxis3 - rightShoulder3D;
        //        //            double rightShoulderAngleAxis3 = Vector3D.AngleBetween(rightShoulderV1Axis3, rightShoulderV2Axis3);
        //        //            now = Math.Round(rightShoulderAngleAxis3, 3);
        //        //            if (!now.IsNaN())
        //        //            {
        //        //                switch (maxJoint17 == 0 && minJoint17 == 0)
        //        //                {
        //        //                    case true:
        //        //                        maxJoint17 = now;
        //        //                        minJoint17 = now;
        //        //                        break;
        //        //                }

        //        //                switch (now > maxJoint17)
        //        //                {
        //        //                    case true:
        //        //                        maxJoint17 = now;
        //        //                        break;
        //        //                }
        //        //                switch (now < minJoint17)
        //        //                {
        //        //                    case true:
        //        //                        minJoint17 = now;
        //        //                        break;
        //        //                }

        //        //                DataRow rw = dt.NewRow();
        //        //                dt.Rows.Add(rw);
        //        //                rw["Joint"] = "Right Shoulder Z";
        //        //                rw["Max Angle"] = maxJoint17.ToString();
        //        //                rw["Min Angle"] = minJoint17.ToString();

        //        //            }
        //        //            #endregion

        //        //            #region leftElbow

        //        //            Vector3D leftElbowV1 = leftShoulder3D - leftElbow3D;
        //        //            Vector3D leftElbowV2 = leftHand3D - leftElbow3D;
        //        //            double leftElbowAngle = Vector3D.AngleBetween(leftElbowV1, leftElbowV2);
        //        //            now = Math.Round(leftElbowAngle, 3);
        //        //            if (!now.IsNaN())
        //        //            {
        //        //                switch (maxJoint4 == 0 && minJoint4 == 0)
        //        //                {
        //        //                    case true:
        //        //                        maxJoint4 = now;
        //        //                        minJoint4 = now;
        //        //                        break;
        //        //                }

        //        //                switch (now > maxJoint4)
        //        //                {
        //        //                    case true:
        //        //                        maxJoint4 = now;
        //        //                        break;
        //        //                }
        //        //                switch (now < minJoint4)
        //        //                {
        //        //                    case true:
        //        //                        minJoint4 = now;
        //        //                        break;
        //        //                }

        //        //                DataRow rw2 = dt.NewRow();
        //        //                dt.Rows.Add(rw2);
        //        //                rw2["Joint"] = "Left Elbow";
        //        //                rw2["Max Angle"] = maxJoint4.ToString();
        //        //                rw2["Min Angle"] = minJoint4.ToString();
        //        //            }
        //        //            #endregion
        //        //            #region rightElbow

        //        //            Vector3D rightElbowV1 = rightShoulder3D - rightElbow3D;
        //        //            Vector3D rightElbowV2 = rightHand3D - rightElbow3D;
        //        //            double rightElbowAngle = Vector3D.AngleBetween(rightElbowV1, rightElbowV2);
        //        //            now = Math.Round(rightElbowAngle, 3);
        //        //            if (!now.IsNaN())
        //        //            {
        //        //                switch (maxJoint5 == 0 && minJoint5 == 0)
        //        //                {
        //        //                    case true:
        //        //                        maxJoint5 = now;
        //        //                        minJoint5 = now;
        //        //                        break;
        //        //                }

        //        //                switch (now > maxJoint5)
        //        //                {
        //        //                    case true:
        //        //                        maxJoint5 = now;
        //        //                        break;
        //        //                }
        //        //                switch (now < minJoint5)
        //        //                {
        //        //                    case true:
        //        //                        minJoint5 = now;
        //        //                        break;
        //        //                }

        //        //                DataRow rw3 = dt.NewRow();
        //        //                dt.Rows.Add(rw3);
        //        //                rw3["Joint"] = "Right Elbow";
        //        //                rw3["Max Angle"] = maxJoint5.ToString();
        //        //                rw3["Min Angle"] = minJoint5.ToString();
        //        //            }
        //        //            #endregion
        //        //            #region Torso

        //        //            Vector3D spine = waist3D - neck3D;
        //        //            Vector3D leftShoulder = leftShoulder3D - neck3D;
        //        //            double Torso = Vector3D.AngleBetween(spine, leftShoulder);
        //        //            now = Math.Round(Torso, 3);
        //        //            if (!now.IsNaN())
        //        //            {
        //        //                switch (maxJoint8 == 0 && minJoint8 == 0)
        //        //                {
        //        //                    case true:
        //        //                        maxJoint8 = now;
        //        //                        minJoint8 = now;
        //        //                        break;
        //        //                }

        //        //                switch (now > maxJoint8)
        //        //                {
        //        //                    case true:
        //        //                        maxJoint8 = now;
        //        //                        break;
        //        //                }
        //        //                switch (now < minJoint8)
        //        //                {
        //        //                    case true:
        //        //                        minJoint8 = now;
        //        //                        break;
        //        //                }

        //        //                DataRow rw4 = dt.NewRow();
        //        //                dt.Rows.Add(rw4);
        //        //                rw4["Joint"] = "Waist";
        //        //                rw4["Max Angle"] = maxJoint8.ToString();
        //        //                rw4["Min Angle"] = minJoint8.ToString();
        //        //            }
        //        //            #endregion
        //        //            #region Left hips Y

        //        //            Vector3D leftHipV1 = rightKnee3D - leftHip3D;
        //        //            Vector3D leftHipV2 = leftKnee3D - leftHip3D;
        //        //            double leftHipAngle = Vector3D.AngleBetween(leftHipV1, leftHipV2);
        //        //            now = Math.Round(leftHipAngle, 3);
        //        //            if (!now.IsNaN())
        //        //            {
        //        //                switch (maxJoint9 == 0 && minJoint9 == 0)
        //        //                {
        //        //                    case true:
        //        //                        maxJoint9 = now;
        //        //                        minJoint9 = now;
        //        //                        break;
        //        //                }

        //        //                switch (now > maxJoint9)
        //        //                {
        //        //                    case true:
        //        //                        maxJoint9 = now;
        //        //                        break;
        //        //                }
        //        //                switch (now < minJoint9)
        //        //                {
        //        //                    case true:
        //        //                        minJoint9 = now;
        //        //                        break;
        //        //                }


        //        //                DataRow rw5 = dt.NewRow();
        //        //                dt.Rows.Add(rw5);
        //        //                rw5["Joint"] = "Left Hip Y";
        //        //                rw5["Max Angle"] = maxJoint9.ToString();
        //        //                rw5["Min Angle"] = minJoint9.ToString();
        //        //            }
        //        //            #endregion
        //        //            #region Left hips Z
        //        //            Vector3D leftHipV1Axis3 = fakeLeftHipX3DAxis3 - leftHip3D;
        //        //            Vector3D leftHipV2Axis3 = leftKnee3D - leftHip3D;
        //        //            double leftHipAngleAxis3 = Vector3D.AngleBetween(leftHipV1Axis3, leftHipV2Axis3);
        //        //            now = Math.Round(leftHipAngleAxis3, 3);
        //        //            if (!now.IsNaN())
        //        //            {
        //        //                switch (maxJoint19 == 0 && minJoint19 == 0)
        //        //                {
        //        //                    case true:
        //        //                        maxJoint19 = now;
        //        //                        minJoint19 = now;
        //        //                        break;
        //        //                }

        //        //                switch (now > maxJoint19)
        //        //                {
        //        //                    case true:
        //        //                        maxJoint19 = now;
        //        //                        break;
        //        //                }
        //        //                switch (now < minJoint19)
        //        //                {
        //        //                    case true:
        //        //                        minJoint19 = now;
        //        //                        break;
        //        //                }

        //        //                DataRow rw = dt.NewRow();
        //        //                dt.Rows.Add(rw);
        //        //                rw["Joint"] = "Left Hip Z";
        //        //                rw["Max Angle"] = maxJoint19.ToString();
        //        //                rw["Min Angle"] = minJoint19.ToString();
        //        //            }
        //        //            #endregion
        //        //            #region Right hips Y

        //        //            Vector3D rightHipV1 = leftKnee3D - rightHip3D;
        //        //            Vector3D rightHipV2 = rightKnee3D - rightHip3D;
        //        //            double rightHipAngle = Vector3D.AngleBetween(rightHipV1, rightHipV2);
        //        //            now = Math.Round(rightHipAngle, 3);
        //        //            if (!now.IsNaN())
        //        //            {
        //        //                switch (maxJoint10 == 0 && minJoint10 == 0)
        //        //                {
        //        //                    case true:
        //        //                        maxJoint10 = now;
        //        //                        minJoint10 = now;
        //        //                        break;
        //        //                }

        //        //                switch (now > maxJoint10)
        //        //                {
        //        //                    case true:
        //        //                        maxJoint10 = now;
        //        //                        break;
        //        //                }
        //        //                switch (now < minJoint10)
        //        //                {
        //        //                    case true:
        //        //                        minJoint10 = now;
        //        //                        break;
        //        //                }

        //        //                DataRow rw6 = dt.NewRow();
        //        //                dt.Rows.Add(rw6);
        //        //                rw6["Joint"] = "Right Hip Y";
        //        //                rw6["Max Angle"] = maxJoint10.ToString();
        //        //                rw6["Min Angle"] = minJoint10.ToString();
        //        //            }
        //        //            #endregion
        //        //            #region Right hips Z
        //        //            Vector3D rightHipV1Axis3 = fakeRightHipX3DAxis3 - rightHip3D;
        //        //            Vector3D rightHipV2Axis3 = rightKnee3D - rightHip3D;
        //        //            double rightHipAngleAxis3 = Vector3D.AngleBetween(rightHipV1Axis3, rightHipV2Axis3);
        //        //            now = Math.Round(rightHipAngleAxis3, 3);
        //        //            if (!now.IsNaN())
        //        //            {
        //        //                switch (maxJoint21 == 0 && minJoint21 == 0)
        //        //                {
        //        //                    case true:
        //        //                        maxJoint21 = now;
        //        //                        minJoint21 = now;
        //        //                        break;
        //        //                }

        //        //                switch (now > maxJoint21)
        //        //                {
        //        //                    case true:
        //        //                        maxJoint21 = now;
        //        //                        break;
        //        //                }
        //        //                switch (now < minJoint21)
        //        //                {
        //        //                    case true:
        //        //                        minJoint21 = now;
        //        //                        break;
        //        //                }

        //        //                DataRow rw = dt.NewRow();
        //        //                dt.Rows.Add(rw);
        //        //                rw["Joint"] = "Right Hip Z";
        //        //                rw["Max Angle"] = maxJoint21.ToString();
        //        //                rw["Min Angle"] = minJoint21.ToString();
        //        //            }
        //        //            #endregion
        //        //            #region leftknee

        //        //            Vector3D leftKneeV1 = leftHip3D - leftKnee3D;
        //        //            Vector3D leftKneeV2 = leftFoot3D - leftKnee3D;
        //        //            double leftKneeAngle = Vector3D.AngleBetween(leftKneeV1, leftKneeV2);
        //        //            now = Math.Round(leftKneeAngle, 3);
        //        //            if (!now.IsNaN())
        //        //            {
        //        //                switch (maxJoint11 == 0 && minJoint11 == 0)
        //        //                {
        //        //                    case true:
        //        //                        maxJoint11 = now;
        //        //                        minJoint11 = now;
        //        //                        break;
        //        //                }

        //        //                switch (now > maxJoint11)
        //        //                {
        //        //                    case true:
        //        //                        maxJoint11 = now;
        //        //                        break;
        //        //                }
        //        //                switch (now < minJoint11)
        //        //                {
        //        //                    case true:
        //        //                        minJoint11 = now;
        //        //                        break;
        //        //                }

        //        //                DataRow rw7 = dt.NewRow();
        //        //                dt.Rows.Add(rw7);
        //        //                rw7["Joint"] = "Left Knee";
        //        //                rw7["Max Angle"] = maxJoint11.ToString();
        //        //                rw7["Min Angle"] = minJoint11.ToString();
        //        //            }
        //        //            #endregion
        //        //            #region rightknee

        //        //            Vector3D rightKneeV1 = rightHip3D - rightKnee3D;
        //        //            Vector3D rightKneeV2 = rightFoot3D - rightKnee3D;
        //        //            double rightKneeAngle = Vector3D.AngleBetween(rightKneeV1, rightKneeV2);
        //        //            now = Math.Round(rightKneeAngle, 3);
        //        //            if (!now.IsNaN())
        //        //            {
        //        //                switch (maxJoint12 == 0 && minJoint12 == 0)
        //        //                {
        //        //                    case true:
        //        //                        maxJoint12 = now;
        //        //                        minJoint12 = now;
        //        //                        break;
        //        //                }

        //        //                switch (now > maxJoint12)
        //        //                {
        //        //                    case true:
        //        //                        maxJoint12 = now;
        //        //                        break;
        //        //                }
        //        //                switch (now < minJoint12)
        //        //                {
        //        //                    case true:
        //        //                        minJoint12 = now;
        //        //                        break;
        //        //                }

        //        //                DataRow rw8 = dt.NewRow();
        //        //                dt.Rows.Add(rw8);
        //        //                rw8["Joint"] = "Right Knee";
        //        //                rw8["Max Angle"] = maxJoint12.ToString();
        //        //                rw8["Min Angle"] = minJoint12.ToString();
        //        //            }
        //        //            #endregion

        //        //            lblLeftElbow = new Label();

        //        //            lblLeftElbow.Width = 200;
        //        //            lblLeftElbow.Height = 100;
        //        //            lblLeftElbow.FontSize = 40;
        //        //            //lblLeftElbow.Content = Math.Round(leftElbowAngle, 3).ToString();
        //        //            lblLeftElbow.Margin = new Thickness(leftElbowX - 100, leftElbowY + 30, 0, 0);
        //        //            if (!showJointLabel)
        //        //            {
        //        //                lblLeftElbow.Visibility = Visibility.Collapsed;
        //        //            }
        //        //            //skeleton.Children.Add(lblLeftElbow);
        //        //            #region display result

        //        //            datagrid2.ItemsSource = ds.Tables[0].DefaultView;

        //        //            #endregion

        //        //            #endregion
        //        //        }

        //        //        //#region Draw skeleton points
        //        //        //if (headX != 0 && headY != 0)
        //        //        //{
        //        //        //    #region DrawLine for joints
        //        //        //    Line myNeck = new Line();
        //        //        //    myNeck.Stroke = Brushes.Black;
        //        //        //    myNeck.X1 = Convert.ToDouble(headX + 15);
        //        //        //    myNeck.Y1 = Convert.ToDouble(headY + 15);
        //        //        //    myNeck.X2 = Convert.ToDouble(neckX + 15);
        //        //        //    myNeck.Y2 = Convert.ToDouble(neckY + 15);
        //        //        //    myNeck.StrokeThickness = 5;
        //        //        //    skeleton.Children.Add(myNeck);

        //        //        //    Line myRightUpperLimbLower = new Line();
        //        //        //    myRightUpperLimbLower.Stroke = Brushes.Black;
        //        //        //    myRightUpperLimbLower.X1 = Convert.ToDouble(rightElbowX + 15);
        //        //        //    myRightUpperLimbLower.Y1 = Convert.ToDouble(rightElbowY + 15);
        //        //        //    myRightUpperLimbLower.X2 = Convert.ToDouble(rightHandX + 15);
        //        //        //    myRightUpperLimbLower.Y2 = Convert.ToDouble(rightHandY + 15);
        //        //        //    myRightUpperLimbLower.StrokeThickness = 5;
        //        //        //    skeleton.Children.Add(myRightUpperLimbLower);

        //        //        //    Line myRightUpperLimbUpper = new Line();
        //        //        //    myRightUpperLimbUpper.Stroke = Brushes.Black;
        //        //        //    myRightUpperLimbUpper.X1 = Convert.ToDouble(rightElbowX + 15);
        //        //        //    myRightUpperLimbUpper.Y1 = Convert.ToDouble(rightElbowY + 15);
        //        //        //    myRightUpperLimbUpper.X2 = Convert.ToDouble(rightShoulderX + 15);
        //        //        //    myRightUpperLimbUpper.Y2 = Convert.ToDouble(rightShoulderY + 15);
        //        //        //    myRightUpperLimbUpper.StrokeThickness = 5;
        //        //        //    skeleton.Children.Add(myRightUpperLimbUpper);

        //        //        //    Line myRightShoulder = new Line();
        //        //        //    myRightShoulder.Stroke = Brushes.Black;
        //        //        //    myRightShoulder.X1 = Convert.ToDouble(neckX + 15);
        //        //        //    myRightShoulder.Y1 = Convert.ToDouble(neckY + 15);
        //        //        //    myRightShoulder.X2 = Convert.ToDouble(rightShoulderX + 15);
        //        //        //    myRightShoulder.Y2 = Convert.ToDouble(rightShoulderY + 15);
        //        //        //    myRightShoulder.StrokeThickness = 5;
        //        //        //    skeleton.Children.Add(myRightShoulder);

        //        //        //    Line myLeftUpperLimbLower = new Line();
        //        //        //    myLeftUpperLimbLower.Stroke = Brushes.Black;
        //        //        //    myLeftUpperLimbLower.X1 = Convert.ToDouble(leftElbowX + 15);
        //        //        //    myLeftUpperLimbLower.Y1 = Convert.ToDouble(leftElbowY + 15);
        //        //        //    myLeftUpperLimbLower.X2 = Convert.ToDouble(leftHandX + 15);
        //        //        //    myLeftUpperLimbLower.Y2 = Convert.ToDouble(leftHandY + 15);
        //        //        //    myLeftUpperLimbLower.StrokeThickness = 5;
        //        //        //    skeleton.Children.Add(myLeftUpperLimbLower);

        //        //        //    Line myLeftUpperLimbUpper = new Line();
        //        //        //    myLeftUpperLimbUpper.Stroke = Brushes.Black;
        //        //        //    myLeftUpperLimbUpper.X1 = Convert.ToDouble(leftElbowX + 15);
        //        //        //    myLeftUpperLimbUpper.Y1 = Convert.ToDouble(leftElbowY + 15);
        //        //        //    myLeftUpperLimbUpper.X2 = Convert.ToDouble(leftShoulderX + 15);
        //        //        //    myLeftUpperLimbUpper.Y2 = Convert.ToDouble(leftShoulderY + 15);
        //        //        //    myLeftUpperLimbUpper.StrokeThickness = 5;
        //        //        //    skeleton.Children.Add(myLeftUpperLimbUpper);

        //        //        //    Line myLeftShoulder = new Line();
        //        //        //    myLeftShoulder.Stroke = Brushes.Black;
        //        //        //    myLeftShoulder.X1 = Convert.ToDouble(neckX + 15);
        //        //        //    myLeftShoulder.Y1 = Convert.ToDouble(neckY + 15);
        //        //        //    myLeftShoulder.X2 = Convert.ToDouble(leftShoulderX + 15);
        //        //        //    myLeftShoulder.Y2 = Convert.ToDouble(leftShoulderY + 15);
        //        //        //    myLeftShoulder.StrokeThickness = 5;
        //        //        //    skeleton.Children.Add(myLeftShoulder);

        //        //        //    //Legs
        //        //        //    Line myLeftLowerLimbLower = new Line();
        //        //        //    myLeftLowerLimbLower.Stroke = Brushes.Black;
        //        //        //    myLeftLowerLimbLower.X1 = Convert.ToDouble(leftFootX + 15);
        //        //        //    myLeftLowerLimbLower.Y1 = Convert.ToDouble(leftFootY + 15);
        //        //        //    myLeftLowerLimbLower.X2 = Convert.ToDouble(leftKneeX + 15);
        //        //        //    myLeftLowerLimbLower.Y2 = Convert.ToDouble(leftKneeY + 15);
        //        //        //    myLeftLowerLimbLower.StrokeThickness = 5;
        //        //        //    skeleton.Children.Add(myLeftLowerLimbLower);

        //        //        //    Line myLeftLowerLimbUpper = new Line();
        //        //        //    myLeftLowerLimbUpper.Stroke = Brushes.Black;
        //        //        //    myLeftLowerLimbUpper.X1 = Convert.ToDouble(leftKneeX + 15);
        //        //        //    myLeftLowerLimbUpper.Y1 = Convert.ToDouble(leftKneeY + 15);
        //        //        //    myLeftLowerLimbUpper.X2 = Convert.ToDouble(leftHipX + 15);
        //        //        //    myLeftLowerLimbUpper.Y2 = Convert.ToDouble(leftHipY + 15);
        //        //        //    myLeftLowerLimbUpper.StrokeThickness = 5;
        //        //        //    skeleton.Children.Add(myLeftLowerLimbUpper);

        //        //        //    Line myRightLowerLimbLower = new Line();
        //        //        //    myRightLowerLimbLower.Stroke = Brushes.Black;
        //        //        //    myRightLowerLimbLower.X1 = Convert.ToDouble(rightFootX + 15);
        //        //        //    myRightLowerLimbLower.Y1 = Convert.ToDouble(rightFootY + 15);
        //        //        //    myRightLowerLimbLower.X2 = Convert.ToDouble(rightKneeX + 15);
        //        //        //    myRightLowerLimbLower.Y2 = Convert.ToDouble(rightKneeY + 15);
        //        //        //    myRightLowerLimbLower.StrokeThickness = 5;
        //        //        //    skeleton.Children.Add(myRightLowerLimbLower);

        //        //        //    Line myRightLowerLimbUpper = new Line();
        //        //        //    myRightLowerLimbUpper.Stroke = Brushes.Black;
        //        //        //    myRightLowerLimbUpper.X1 = Convert.ToDouble(rightKneeX + 15);
        //        //        //    myRightLowerLimbUpper.Y1 = Convert.ToDouble(rightKneeY + 15);
        //        //        //    myRightLowerLimbUpper.X2 = Convert.ToDouble(rightHipX + 15);
        //        //        //    myRightLowerLimbUpper.Y2 = Convert.ToDouble(rightHipY + 15);
        //        //        //    myRightLowerLimbUpper.StrokeThickness = 5;
        //        //        //    skeleton.Children.Add(myRightLowerLimbUpper);

        //        //        //    Line myLeftLowerWrist = new Line();
        //        //        //    myLeftLowerWrist.Stroke = Brushes.Black;
        //        //        //    myLeftLowerWrist.X1 = Convert.ToDouble(waistX + 15);
        //        //        //    myLeftLowerWrist.Y1 = Convert.ToDouble(waistY + 15);
        //        //        //    myLeftLowerWrist.X2 = Convert.ToDouble(leftHipX + 15);
        //        //        //    myLeftLowerWrist.Y2 = Convert.ToDouble(leftHipY + 15);
        //        //        //    myLeftLowerWrist.StrokeThickness = 5;
        //        //        //    skeleton.Children.Add(myLeftLowerWrist);

        //        //        //    Line myRightLowerWrist = new Line();
        //        //        //    myRightLowerWrist.Stroke = Brushes.Black;
        //        //        //    myRightLowerWrist.X1 = Convert.ToDouble(waistX + 15);
        //        //        //    myRightLowerWrist.Y1 = Convert.ToDouble(waistY + 15);
        //        //        //    myRightLowerWrist.X2 = Convert.ToDouble(rightHipX + 15);
        //        //        //    myRightLowerWrist.Y2 = Convert.ToDouble(rightHipY + 15);
        //        //        //    myRightLowerWrist.StrokeThickness = 5;
        //        //        //    skeleton.Children.Add(myRightLowerWrist);

        //        //        //    Line myLeftUpperWrist = new Line();
        //        //        //    myLeftUpperWrist.Stroke = Brushes.Black;
        //        //        //    myLeftUpperWrist.X1 = Convert.ToDouble(waistX + 15);
        //        //        //    myLeftUpperWrist.Y1 = Convert.ToDouble(waistY + 15);
        //        //        //    myLeftUpperWrist.X2 = Convert.ToDouble(leftShoulderX + 15);
        //        //        //    myLeftUpperWrist.Y2 = Convert.ToDouble(leftShoulderY + 15);
        //        //        //    myLeftUpperWrist.StrokeThickness = 5;
        //        //        //    skeleton.Children.Add(myLeftUpperWrist);

        //        //        //    Line myRightUpperWrist = new Line();
        //        //        //    myRightUpperWrist.Stroke = Brushes.Black;
        //        //        //    myRightUpperWrist.X1 = Convert.ToDouble(waistX + 15);
        //        //        //    myRightUpperWrist.Y1 = Convert.ToDouble(waistY + 15);
        //        //        //    myRightUpperWrist.X2 = Convert.ToDouble(rightShoulderX + 15);
        //        //        //    myRightUpperWrist.Y2 = Convert.ToDouble(rightShoulderY + 15);
        //        //        //    myRightUpperWrist.StrokeThickness = 5;
        //        //        //    skeleton.Children.Add(myRightUpperWrist);
        //        //        //    #endregion

        //        //        //    #region DrawCircle for each point
        //        //        //    DrawCircle(headX, headY, userColor);
        //        //        //    //DrawCircle(neckX, neckY, userColor);
        //        //        //    //DrawCircle(leftShoulderX, leftShoulderY, userColor);
        //        //        //    //DrawCircle(leftElbowX, leftElbowY, userColor);
        //        //        //    //DrawCircle(leftHandX, leftHandY, userColor);
        //        //        //    //DrawCircle(waistX, waistY, userColor);
        //        //        //    //DrawCircle(rightShoulderX, rightShoulderY, userColor);
        //        //        //    //DrawCircle(rightElbowX, rightElbowY, userColor);
        //        //        //    //DrawCircle(rightHandX, rightHandY, userColor);
        //        //        //    //DrawCircle(leftHipX, leftHipY, userColor);
        //        //        //    //DrawCircle(leftKneeX, leftKneeY, userColor);
        //        //        //    //DrawCircle(leftFootX, leftFootY, userColor);
        //        //        //    //DrawCircle(rightHipX, rightHipY, userColor);
        //        //        //    //DrawCircle(rightKneeX, rightKneeY, userColor);
        //        //        //    //DrawCircle(rightFootX, rightFootY, userColor);
        //        //        //    gotUser = true;
        //        //        //    #endregion
        //        //        //}
        //        //        //else
        //        //        //{
        //        //        //    stopKinect();
        //        //        //    startKinect();
        //        //        //}
        //        //        //#endregion

        //        //        //#region Draw skeleton points
        //        //        //if (headX != 0 && headY != 0)
        //        //        //{
        //        //        //    #region DrawCircle for each point
        //        //        //    DrawCircle(headX, headY, userColor);
        //        //        //    DrawCircle(neckX, neckY, userColor);
        //        //        //    DrawCircle(leftShoulderX, leftShoulderY, userColor);
        //        //        //    DrawCircle(leftElbowX, leftElbowY, userColor);
        //        //        //    DrawCircle(leftHandX, leftHandY, userColor);
        //        //        //    DrawCircle(waistX, waistY, userColor);
        //        //        //    DrawCircle(rightShoulderX, rightShoulderY, userColor);
        //        //        //    DrawCircle(rightElbowX, rightElbowY, userColor);
        //        //        //    DrawCircle(rightHandX, rightHandY, userColor);
        //        //        //    DrawCircle(leftHipX, leftHipY, userColor);
        //        //        //    DrawCircle(leftKneeX, leftKneeY, userColor);
        //        //        //    DrawCircle(leftFootX, leftFootY, userColor);
        //        //        //    DrawCircle(rightHipX, rightHipY, userColor);
        //        //        //    DrawCircle(rightKneeX, rightKneeY, userColor);
        //        //        //    DrawCircle(rightFootX, rightFootY, userColor);
        //        //        //    gotUser = true;
        //        //        //    #endregion
        //        //        //}
        //        //        //else
        //        //        //{
        //        //        //    stopKinect();
        //        //        //    startKinect();
        //        //        //}
        //        //        //#endregion
        //        //    }
        //        //});
        //        //#endregion
        //    }
        //}
        #endregion
        void DrawCircle(float positionX, float positionY, Color color)
        {
            Ellipse ellipse = new Ellipse
            {
                Fill = new SolidColorBrush(color),
                Width = 30,
                Height = 30,
                Margin = new Thickness(positionX, positionY + 15, 0, 0)
            };

            skeleton.Children.Add(ellipse);
        }

        #region AngleAnalysis

        bool start = true;
        bool createdSession = false;

        //start stage
        private void btn_start_MouseDown(object sender, MouseButtonEventArgs e)
        {
            sp_k_field.Visibility = Visibility.Visible;
            if (start)
            {

                dif = 0;
                max = 0;
                min = 0;
                maxActive = 0;
                maxPassive = 0;
                minActive = 0;
                minPassive = 0;
                lowSystemTime = DateTime.Now;

                lbl_k_max.Text = "0";
                lbl_k_min.Text = "0";
                lbl_k_max_passive.Text = "0";
                lbl_k_min_passive.Text = "0";
            }
            else
            {
                dif = 0;
                max = 0;
                min = 0;
                maxActive = 0;
                maxPassive = 0;
                minActive = 0;
                minPassive = 0;
                lowSystemTime = DateTime.Now;

                lbl_k_max.Text = "0";
                lbl_k_min.Text = "0";
                lbl_k_max_passive.Text = "0";
                lbl_k_min_passive.Text = "0";

                tbx_joint_Copy.Text = al[cot].ToString();
                showStage();
                lbScore.SelectedIndex = 0;
                btn_start.IsEnabled = true;
                BitmapImage bi = new BitmapImage(new Uri("restart.png", UriKind.Relative));
                btn_proceed.Visibility = Visibility.Visible;
                btn_start.Source = bi;
                start = true;
            }
        }

        int cot = -1;//Count the stages
        ServiceReference2.EXE currentExe = new ServiceReference2.EXE();
        int currentSessionID = 0;
        private void btn_proceed_MouseDown(object sender, MouseButtonEventArgs e)
        {
            sp_k_stage.Visibility = Visibility.Visible;

            if (lbScore.SelectedIndex != 0)//record scoring and angleing
            {
                if (cot != -1)
                {
                    if (start)
                    {

                        currentExe.Uid = 1;
                        if (checkbx_active.IsChecked == true)
                        {
                            angleing.Add(lbl_k_max.Text);
                            angleing.Add(lbl_k_min.Text);

                        }
                        else
                        {
                            angleing.Add(lbl_k_max_passive.Text);
                            angleing.Add(lbl_k_min_passive.Text);
                        }

                        scoring.Add((lbScore.SelectedIndex - 1).ToString());
                        listofdif.Add(dif.ToString());

                        if (createdSession == false)
                        {
                            try
                            {
                                currentSessionID = svc.createNewSession(p.Uid, currentExe.Uid);
                                createdSession = true;
                            }
                            catch (Exception) { }
                        }
                        //else
                        //{
                        //    try
                        //    {
                        //        currentSessionID = 0 = svc.retrieveMostRecentSessionIDOfPatientofExe(p.Uid, currentExe.Uid);
                        //    }
                        //    catch (Exception) { }
                        //}
                        try
                        {
                            string description = "";
                            string jointName = svc.retrieveJointName(al[cot].ToString());
                            if (Convert.ToDouble(lbl_k_min.Text) != 0 & Convert.ToDouble(lbl_k_min.Text).IsNaN() == false)
                            {
                                description = jointName + " : " + "Patient can move from ";
                                //svc.createNewGamePlayCompleted += new EventHandler<ServiceReference2.createNewGamePlayCompletedEventArgs>(svc_createNewGamePlayCompleted);
                                svc.createNewGamePlayAsync(currentSessionID, cot + 1, al[cot].ToString(), tbxSpecialInstruction.Text, "Active Angle Min (Degree)", lbl_k_min.Text);
                                description += lbl_k_min.Text + " degrees to ";

                            }
                            if (Convert.ToDouble(lbl_k_max.Text) != 0 && Convert.ToDouble(lbl_k_max.Text).IsNaN() == false)
                            {
                                svc.createNewGamePlayAsync(currentSessionID, cot + 1, al[cot].ToString(), tbxSpecialInstruction.Text, "Active Angle Max (Degree)", lbl_k_max.Text);
                                description += lbl_k_max.Text + " degrees.;";
                            }


                            if (Convert.ToDouble(lbl_k_min_passive.Text) != 0 && Convert.ToDouble(lbl_k_min_passive.Text).IsNaN() == false)
                            {
                                description += jointName + " : " + "Patient can move from " + lbl_k_min_passive.Text + " degrees to ";
                                svc.createNewGamePlayAsync(currentSessionID, cot + 1, al[cot].ToString(), tbxSpecialInstruction.Text, "Passive Angle Min (Degree)", lbl_k_min_passive.Text);

                            }
                            if (Convert.ToDouble(lbl_k_max_passive.Text) != 0 && Convert.ToDouble(lbl_k_max_passive.Text).IsNaN() == false)
                            {
                                svc.createNewGamePlayAsync(currentSessionID, cot + 1, al[cot].ToString(), tbxSpecialInstruction.Text, "Passive Angle Max (Degree)", lbl_k_max_passive.Text);
                                description += lbl_k_max_passive.Text + " degrees (Passive).; ";
                            }

                            svc.createNewGamePlayAsync(currentSessionID, cot + 1, al[cot].ToString(), tbxSpecialInstruction.Text, "Score (Points)", (lbScore.SelectedIndex - 1).ToString());
                            svc.createNewGamePlayAsync(currentSessionID, cot + 1, al[cot].ToString(), tbxSpecialInstruction.Text, "Time (Seconds)", dif.ToString());

                            svc.updateProblem2(Convert.ToInt16(tbx_joint_Copy.Text), p.Uid, description, tbxSpecialInstruction.Text);
                        }
                        catch (Exception) { }
                        tbxSpecialInstruction.Text = "";
                    }
                }
            }
            if (!start)
            {
                MessageBox.Show("Please finish with this test before proceeding");
            }
            else
            {
                if (lbScore.SelectedIndex == 0)//Check for empty input
                {
                    MessageBox.Show("Please enter a scoring for this stage");
                }
                else
                {
                    if (al.Count != cot + 1)
                    {
                        if (start)
                        {
                            //change radio button
                            btn_start.Source = new BitmapImage(new Uri("start.png", UriKind.Relative));
                            start = false;
                            btn_start.IsEnabled = true;
                            sp_k_field.Visibility = Visibility.Collapsed;
                            //Do Opposite

                            cot++;
                            lblStage.Text = "Fugl-Meyer:";
                            lbl_stage.Text = "Stage " + (cot + 1);
                            tbx_joint_Copy.Text = al[cot].ToString();
                            tbx_joint_Copy.Text = returnOpp(tbx_joint_Copy.Text); //Find opposite joint
                            showStage();
                            lbl_k_jointName.Text = "Testing: " + lbl_k_jointName.Text;
                            dif = 0;
                            max = 0;
                            min = 0;
                            maxActive = 0;
                            maxPassive = 0;
                            minActive = 0;
                            minPassive = 0;
                            lbl_k_max.Text = "0";
                            lbl_k_min.Text = "0";
                            lbl_k_max_passive.Text = "0";
                            lbl_k_min_passive.Text = "0";
                            lbScore.SelectedIndex = 0;
                            //Do Opposite
                            btn_proceed.Visibility = Visibility.Collapsed;
                        }
                        else
                        { }
                    }
                    else //End the the stages
                    {
                        lbl_k_jointName.Text = "End of Session";
                        btn_proceed.IsEnabled = false;
                        btn_start.IsEnabled = false;
                        lbScore.IsEnabled = false;
                        lbScore.SelectedIndex = 0;
                        cot = 0;
                        sp_k_controlPanel.Visibility = Visibility.Collapsed;
                        sp_k_controlPanel_start.Visibility = Visibility.Collapsed;
                        btn_start.Visibility = Visibility.Collapsed;
                        btn_proceed.Visibility = Visibility.Collapsed;
                    }
                }
            }

        }



        //Start Fugl Meyer
        private void sp_k_controlPanel_start_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            sp_k_controlPanel_start.Visibility = Visibility.Collapsed;
            sp_k_controlPanel.Visibility = Visibility.Visible;
            sp_k_stage.Visibility = Visibility.Visible;


            //change radio button
            cot = -1;
            btn_start.Source = new BitmapImage(new Uri("start.png", UriKind.Relative));
            btn_start.Visibility = Visibility.Visible;
            btn_proceed.Visibility = Visibility.Collapsed;
            start = false;
            btn_start.IsEnabled = true;
            lbScore.IsEnabled = true;
            //Do Opposite

            cot++;
            lblStage.Text = "Fugl-Meyer:";
            lbl_stage.Text = "Stage " + (cot + 1);
            tbx_joint_Copy.Text = al[cot].ToString();
            tbx_joint_Copy.Text = returnOpp(tbx_joint_Copy.Text); //Find opposite joint
            showStage();
            lbl_k_jointName.Text = "Testing: " + lbl_k_jointName.Text;
            dif = 0;
            lbl_k_max.Text = "0";
            lbl_k_min.Text = "0";
            lbl_k_max_passive.Text = "0";
            lbl_k_min_passive.Text = "0";
            lbScore.SelectedIndex = 0;
            //Do Opposite

            btn_proceed.Visibility = Visibility.Collapsed;
        }

        void svc_retrievePatientProblemsCompleted(object sender, ServiceReference2.retrievePatientProblemsCompletedEventArgs e)
        {
            if (e.Error == null)
            {
                problemList = e.Result;
            }
        }

        void svc_retrieveExeAssignedtoPatientCompleted(object sender, ServiceReference2.retrieveExeAssignedtoPatientCompletedEventArgs e)
        {
            if (e.Error == null)
            {
                exeAssignedList = e.Result;
            }
        }

        private void showStage()
        {
            if (tbx_joint_Copy.Text == "1")
            {
                //lbl_k_jointName.Text = "Neck";
                tbx_joint.Text = "Neck";
            }
            else if (tbx_joint_Copy.Text == "2")
            {
                //lbl_k_jointName.Text = "Left Shoulder: Put your hand on behind your back";
                tbx_joint.Text = "Left Shoulder: Put your hand on behind your back";
            }
            else if (tbx_joint_Copy.Text == "3")
            {
                //lbl_k_jointName.Text = "Right Shoulder";
                tbx_joint.Text = "Right Shoulder";
            }
            else if (tbx_joint_Copy.Text == "4")
            {
                //lbl_k_jointName.Text = "Left Elbow: Finger to nose";
                tbx_joint.Text = "Left Elbow: Finger to nose";
            }
            else if (tbx_joint_Copy.Text == "5")
            {
                //lbl_k_jointName.Text = "Right Elbow";
                tbx_joint.Text = "Right Elbow";
            }
            else if (tbx_joint_Copy.Text == "6")
            {
                //lbl_k_jointName.Text = "Torso";
                tbx_joint.Text = "Torso";
            }
            else if (tbx_joint_Copy.Text == "7")
            {
                //lbl_k_jointName.Text = "Left Hand";
                tbx_joint.Text = "Left Hand";
            }
            else if (tbx_joint_Copy.Text == "8")
            {
                //lbl_k_jointName.Text = "Right Hand";
                tbx_joint.Text = "Right Hand";
            }
            else if (tbx_joint_Copy.Text == "9")
            {
                //lbl_k_jointName.Text = "Left Hip: Heel to opposite knee";
                tbx_joint.Text = "Left Hip: Heel to opposite knee";
            }
            else if (tbx_joint_Copy.Text == "10")
            {
                //lbl_k_jointName.Text = "Right Hip";
                tbx_joint.Text = "Right Hip";
            }
            else if (tbx_joint_Copy.Text == "11")
            {
                //lbl_k_jointName.Text = "Left Knee: Kick your bottom with your heel";
                tbx_joint.Text = "Left Knee: Kick your bottom with your heel";
            }
            else if (tbx_joint_Copy.Text == "12")
            {
                //lbl_k_jointName.Text = "Right Knee";
                tbx_joint.Text = "Right Knee";
            }
            else if (tbx_joint_Copy.Text == "13")
            {
                //lbl_k_jointName.Text = "Left Foot";
                tbx_joint.Text = "Left Foot";
            }
            else if (tbx_joint_Copy.Text == "14")
            {
                //lbl_k_jointName.Text = "Right Foot";
                tbx_joint.Text = "Right Foot";
            }

        }

        private string returnOpp(string joint)
        {
            if (joint == "2")
            {
                return "3";
            }
            if (joint == "3")
            {
                return "2";
            }
            if (joint == "4")
            {
                return "5";
            }
            if (joint == "5")
            {
                return "4";
            }

            if (joint == "7")
            {
                return "8";
            }
            if (joint == "8")
            {
                return "7";
            }
            if (joint == "9")
            {
                return "10";
            }
            if (joint == "10")
            {
                return "9";
            }
            if (joint == "11")
            {
                return "12";
            }
            if (joint == "12")
            {
                return "11";
            }
            if (joint == "13")
            {
                return "14";
            }
            if (joint == "14")
            {
                return "13";
            }
            return joint;
        }

        #endregion

        private void stopKinect()
        {
            //_skeleton.Stop();
            //_worker.CancelAsync();
            //_worker.Dispose();

            try
            {
                try
                {
                    BWstarted = false;
                    _worker.CancelAsync();
                    //if (xmlRead)
                    //{
                    //    _skeleton.StopUserTracking();
                    //    _skeleton.Stop();
                    //    try
                    //    {
                    //        _skeleton = null;
                    //        _skeleton = new NuiUserTracker("");
                    //    }
                    //    catch (Exception) { }
                    //    xmlRead = false;
                    //}


                    //CompositionTarget.Rendering -= CompositionTarget_Rendering;
                    //_skeleton.UserUpdated -= Skeleton_UserUpdated;
                    //_worker.CancelAsync();
                    //_worker.Dispose();
                    //_skeleton = 
                    //skeleton.Children.Clear();
                }
                catch (NullReferenceException) { }
            }
            catch (Exception) { }
            gotUser = false;
        }

        private void startKinect()
        {
            try
            {
                //if (!xmlRead)
                //{
                //    stopping = false;
                //    try
                //    {
                //        //_skeleton = new NuiUserTracker("SamplesConfig.xml");
                //        _skeleton = new NuiUserTracker(xmlPath());
                //    }
                //    catch (Exception) { }
                //    xmlRead = true;
                //    _skeleton.Start();
                //}
                BWstarted = true;
                _worker.RunWorkerAsync();

                //CompositionTarget.Rendering += CompositionTarget_Rendering;
                //_skeleton.UsersUpdated += _skeleton_UsersUpdated;
                //_worker.RunWorkerAsync();
                //skeleton.Children.Clear();
            }
            catch (Exception) { }
            gotUser = false;
        }

        private string xmlPath()
        {
            string result = "";
            switch (xmlCount)
            {
                case 0:
                    result = "SamplesConfig.xml";
                    xmlCount++;
                    break;
                case 1:
                    result = "SamplesConfig1.xml";
                    xmlCount++;
                    break;
                case 2:
                    result = "SamplesConfig2.xml";
                    xmlCount++;
                    //xmlCount = 0;
                    break;
                case 3:
                    result = "SamplesConfig3.xml";
                    xmlCount++;
                    break;
                case 4:
                    result = "SamplesConfig4.xml";
                    xmlCount = 0;
                    break;
            };
            return result;
        }

        # endregion

        #region Treatment Analysis

        // 1st dropdown list
        private void cbxTreatment_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            graph_rangeMotion.Series.Clear();
            cbxPerformance.SelectedIndex = -1;
            cbxYAxis.SelectedIndex = -1;
            sp_Attribute.Visibility = Visibility.Collapsed;
            sp_Stage.Visibility = Visibility.Collapsed;

            if (cbxTreatment.SelectedIndex != -1)
            {
                string treatment = cbxTreatment.SelectedItem.ToString();
                foreach (ServiceReference2.EXE ex in allExeList)
                {
                    if (treatment.Equals(ex.Name))
                    {
                        selectedExe = ex;
                    }
                }

                //if (selectedExe.ExeType == 1)
                //{
                //    btn_addExecute.Visibility = Visibility.Collapsed;
                //}
                //else
                //{
                //    btn_addExecute.Visibility = Visibility.Visible;
                //}

                if (selectedExe.ExeStage.Count != 0) // got stage
                {
                    #region got exestage
                    //cbxPerformance.Visibility = Visibility.Collapsed;
                    //cbxPerformance.IsEnabled = false;
                    sp_Stage.Visibility = Visibility.Visible;
                    sp_Attribute.Visibility = Visibility.Collapsed;

                    List<string> stageNameListDisplay = new List<string>();

                    foreach (ServiceReference2.session patientSession in patientSessionList)
                    {
                        if (patientSession.ExeID == selectedExe.Uid)
                        {
                            List<ServiceReference2.gamePlay> patientGamePlayList = new List<ServiceReference2.gamePlay>();
                            patientGamePlayList = patientSession.GamePlaylist;

                            foreach (ServiceReference2.gamePlay gameplay in patientGamePlayList)
                            {
                                stageNameListDisplay.Add(gameplay.StageName);
                            }
                        }
                    }

                    stageNameListDisplay = stageNameListDisplay.Distinct().ToList();

                    cbxPerformance.ItemsSource = stageNameListDisplay;

                    #endregion
                }
                else
                {
                    #region no stage
                    stageName = "nostage";
                    sp_Attribute.Visibility = Visibility.Visible;
                    List<string> gameKeyList = new List<string>();
                    foreach (ServiceReference2.session patientSession in patientSessionList)
                    {
                        if (patientSession.ExeID == selectedExe.Uid)
                        {
                            List<ServiceReference2.gamePlay> patientGamePlayList = new List<ServiceReference2.gamePlay>();
                            patientGamePlayList = patientSession.GamePlaylist;

                            foreach (ServiceReference2.gamePlay gameplay in patientGamePlayList)
                            {
                                gameKeyList.Add(gameplay.GameKey);
                            }
                        }
                    }

                    gameKeyList = gameKeyList.Distinct().ToList();

                    cbxYAxis.SelectedIndex = -1;
                    cbxYAxis.Items.Clear();
                    foreach (string gameKey in gameKeyList)
                    {
                        CheckBox cbx = new CheckBox();
                        cbx.Checked += new RoutedEventHandler(cbx_Checked);
                        cbx.Unchecked += new RoutedEventHandler(cbx_Unchecked);
                        cbx.Content = gameKey;
                        cbxYAxis.Items.Add(cbx);
                    }

                    #endregion
                }
            }

        }

        // middle one AKA stage
        private void cbxPerformance_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            cbxYAxis.SelectedIndex = -1;
            graph_rangeMotion.Series.Clear();
            datagrid1.ItemsSource = null;
            sp_Attribute.Visibility = Visibility.Collapsed;

            if (cbxPerformance.SelectedIndex != -1)
            {
                stageName = cbxPerformance.SelectedItem.ToString();
                sp_Attribute.Visibility = Visibility.Visible;
                List<string> gameKeyList = new List<string>();
                foreach (ServiceReference2.session patientSession in patientSessionList)
                {
                    if (patientSession.ExeID == selectedExe.Uid)
                    {
                        List<ServiceReference2.gamePlay> patientGamePlayList = new List<ServiceReference2.gamePlay>();
                        patientGamePlayList = patientSession.GamePlaylist;

                        foreach (ServiceReference2.gamePlay gameplay in patientGamePlayList)
                        {
                            if (gameplay.StageName.Equals(stageName))
                            {
                                if (gameplay.GameKey.Contains("Angle X"))
                                {
                                    gameKeyList.Add("Range X");
                                }
                                else if (gameplay.GameKey.Contains("Angle Y"))
                                {
                                    gameKeyList.Add("Range Y");
                                }
                                else if (gameplay.GameKey.Contains("Angle Z"))
                                {
                                    gameKeyList.Add("Range Z");
                                }
                                else if (gameplay.GameKey.Contains("Angle"))
                                {
                                    gameKeyList.Add("Range");
                                }
                                else if (!gameplay.GameKey.Contains("Angle"))
                                {
                                    gameKeyList.Add(gameplay.GameKey);
                                }
                            }
                        }
                    }
                }

                gameKeyList = gameKeyList.Distinct().ToList();

                cbxYAxis.SelectedIndex = -1;
                cbxYAxis.Items.Clear();
                foreach (string gameKey in gameKeyList)
                {
                    CheckBox cbx = new CheckBox();
                    cbx.Content = gameKey;
                    cbx.Checked += new RoutedEventHandler(cbx_Checked);
                    cbx.Unchecked += new RoutedEventHandler(cbx_Unchecked);
                    cbxYAxis.Items.Add(cbx);
                }
            }
        }

        #region checkbox events in 3rd dropdownlist
        void cbx_Unchecked(object sender, RoutedEventArgs e)
        {
            createChart();
            createTable();
        }

        void cbx_Checked(object sender, RoutedEventArgs e)
        {
            createChart();
            createTable();
        }
        #endregion
        bool gotRange = false;
        private void createChart()
        {
            gotRange = false;
            lsList.Clear();
            colorCount = 0;
            graph_rangeMotion.Series.Clear();
            Visiblox.Charts.DateTimeAxis asd = new DateTimeAxis();
            graph_rangeMotion.XAxis = asd;
            bool title = false;
            List<string> selectedKeyList = new List<string>();

            #region check for selected items

            foreach (CheckBox cbx in cbxYAxis.Items)
            {
                if (cbx.IsChecked == true)
                {
                    if (!cbx.Content.ToString().Contains("Range"))
                    {
                        selectedKeyList.Add(cbx.Content.ToString());
                    }
                    else
                    {
                        gotRange = true;
                    }
                }
            }
            #endregion

            #region noRange
            int keyCount = 0;
            for (int i1 = 0; i1 < selectedKeyList.Count; i1++)
            {
                string gameKey = selectedKeyList[i1];
                int count = 0;

                DataSeries<DateTime, double> temp = new DataSeries<DateTime, double>(gameKey);
                int xCount = 0;
                foreach (ServiceReference2.session ps in patientSessionList)
                {
                    if (ps.ExeID == selectedExe.Uid)
                    {
                        List<ServiceReference2.gamePlay> patientGamePlayList = new List<ServiceReference2.gamePlay>();
                        patientGamePlayList = ps.GamePlaylist;

                        List<int> gameplayIDlist = new List<int>();

                        foreach (ServiceReference2.gamePlay gameplay in patientGamePlayList)
                        {
                            if (!gameplayIDlist.Contains(gameplay.Uid))
                            {
                                //if (gameKey.Equals(gameplay.GameKey) && (gameplay.StageName.Equals(stageName) || stageName == "nostage"))
                                if (gameKey.Equals(gameplay.GameKey) && (gameplay.StageName.Equals(stageName) || gameplay.StageName.Equals("nostage")))
                                {
                                    xCount++;
                                    gameplayIDlist.Add(gameplay.Uid);
                                }

                            }
                        }
                    }
                }

                DateTime[] x = new DateTime[xCount];
                double[] y = new double[xCount];

                foreach (ServiceReference2.session patientSession in patientSessionList)
                {
                    string notes = "";
                    if (patientSession.ExeID == selectedExe.Uid)
                    {
                        List<ServiceReference2.gamePlay> patientGamePlayList = new List<ServiceReference2.gamePlay>();
                        patientGamePlayList = patientSession.GamePlaylist;

                        List<int> gameplayIDlist = new List<int>();

                        foreach (ServiceReference2.gamePlay gameplay in patientGamePlayList)
                        {
                            if (!gameplayIDlist.Contains(gameplay.Uid))
                            {
                                if (gameKey.Equals(gameplay.GameKey) && (gameplay.StageName.Equals(stageName) || stageName == "nostage"))
                                {
                                    gameplayIDlist.Add(gameplay.Uid);
                                    x[count] = patientSession.Dateofplay;
                                    y[count] = Convert.ToDouble(gameplay.GameValue);
                                    count++;
                                    if (gameplay.SpecialInstructions != "")
                                    {
                                        try
                                        {
                                            notes += svc.retrieveJointName(gameplay.Joint) + " : " + gameplay.SpecialInstructions + ";";
                                        }
                                        catch (Exception)
                                        {
                                            notes += gameplay.Joint + " : " + gameplay.SpecialInstructions + ";";
                                        }
                                    }

                                    if (title == false)
                                    {
                                        TextBlock textblock = new TextBlock();
                                        SolidColorBrush color = new SolidColorBrush();
                                        color.Color = Colors.White;
                                        textblock.Foreground = color;
                                        textblock.Text = "Notes";
                                        textblock.FontWeight = FontWeights.Bold;
                                        textblock.Margin = new Thickness(0, 5, 0, 5);

                                        title = true;
                                    }


                                }
                            }
                        }
                    }
                    keyCount++;
                }
                for (int i = 0; i < x.Length; i++)
                {
                    temp.Add(new DataPoint<DateTime, double>() { X = x[i], Y = y[i] });
                }
                LineSeries ls = new LineSeries();

                SolidColorBrush color1 = new SolidColorBrush();
                color1.Color = colurList[colorCount];
                ls.LineStroke = color1;
                colorCount++;
                ls.LineStrokeThickness = 4;

                graph_rangeMotion.Series.Add(ls);


                graph_rangeMotion.Series[i1].DataSeries = temp;
            }

            #endregion
            DateTime[] xx = new DateTime[2];
            double[] yy = new double[2];
            double gameValue1 = 0.0;
            double gameValue2 = 0.0;
            #region gotRange
            bool showLegendRange = false;
            if (gotRange == true)
            {

                foreach (ServiceReference2.session patientSession in patientSessionList)
                {
                    DataSeries<DateTime, double> temp = new DataSeries<DateTime, double>("Range");
                    //DateTime[] x = new DateTime[2];
                    //double[] y = new double[2];
                    //double gameValue1 = 0.0;
                    //double gameValue2 = 0.0;
                    if (patientSession.ExeID == selectedExe.Uid)
                    {
                        List<ServiceReference2.gamePlay> patientGamePlayList = new List<ServiceReference2.gamePlay>();
                        patientGamePlayList = patientSession.GamePlaylist;

                        foreach (ServiceReference2.gamePlay gameplay in patientGamePlayList)
                        {
                            if (gameplay.GameKey.Contains("Angle") && (gameplay.StageName.Equals(stageName) || stageName == "nostage"))
                            {
                                if (gameValue1 == 0.0)
                                {
                                    try
                                    {
                                        gameValue1 = Convert.ToDouble(gameplay.GameValue);
                                        xx[0] = patientSession.Dateofplay;
                                        yy[0] = gameValue1;
                                        temp.Add(new DataPoint<DateTime, double>() { X = xx[0], Y = yy[0] });
                                    }
                                    catch (Exception) { }

                                }
                                else
                                {
                                    try
                                    {
                                        gameValue2 = Convert.ToDouble(gameplay.GameValue);
                                        xx[1] = patientSession.Dateofplay;
                                        yy[1] = gameValue2;
                                        temp.Add(new DataPoint<DateTime, double>() { X = xx[1], Y = yy[1] });
                                    }
                                    catch (Exception) { }

                                }

                            }
                        }

                        LineSeries ls = new LineSeries();

                        SolidColorBrush color1 = new SolidColorBrush();
                        color1.Color = Colors.Red;
                        ls.LineStroke = color1;
                        colorCount++;
                        ls.LineStrokeThickness = 4;
                        ls.DataSeries = temp;
                        ls.Visibility = Visibility.Collapsed;
                        lsList.Add(ls);
                        if (showLegendRange == false)
                        {
                            showLegendRange = true;
                        }
                        else
                            ls.IsDisplayedOnLegend = false;
                        graph_rangeMotion.Series.Add(ls);

                    }
                }
            }

            DataSeries<DateTime, double> benchMax = new DataSeries<DateTime, double>("Max Benchmark");
            benchMax.Add(new DataPoint<DateTime, double>() { X = xx[0], Y = 175 });
            benchMax.Add(new DataPoint<DateTime, double>() { X = xx[1], Y = 175 });
            LineSeries ls3 = new LineSeries();

            SolidColorBrush color12 = new SolidColorBrush();
            color12.Color = Colors.Black;
            ls3.LineStroke = color12;
            colorCount++;
            ls3.LineStrokeThickness = 4;
            ls3.DataSeries = benchMax;
            graph_rangeMotion.Series.Add(ls3);

            DataSeries<DateTime, double> bench = new DataSeries<DateTime, double>("Min Benchmark");
            bench.Add(new DataPoint<DateTime, double>() { X = xx[0], Y = 2 });
            bench.Add(new DataPoint<DateTime, double>() { X = xx[1], Y = 2 });
            LineSeries ls4 = new LineSeries();

            SolidColorBrush color124 = new SolidColorBrush();
            color124.Color = Colors.Black;
            ls4.LineStroke = color124;
            colorCount++;
            ls4.LineStrokeThickness = 4;
            ls4.DataSeries = bench;
            graph_rangeMotion.Series.Add(ls4);
            #endregion

            #region unwanted
            //ArrayList gameKey = new ArrayList();
            //string performance = "";
            //cbxYAxis.Visibility = Visibility.Visible;
            //if (cbxPerformance.Visibility == Visibility.Collapsed)
            //{
            //}
            //else
            //{
            //    performance = cbxPerformance.SelectedItem.ToString();
            //}


            ////foreach (ServiceReference2.stage s in stageList)
            ////{
            ////    if (performance.Equals(s.Name))
            ////    {
            ////        id = s.Uid;
            ////        svc.retrieveSessionOfPatientofExeCompleted += new EventHandler<ServiceReference2.retrieveSessionOfPatientofExeCompletedEventArgs>(svc_retrieveSessionOfPatientofExeCompleted);
            ////        svc.retrieveSessionOfPatientofExeAsync(p.Uid, id);
            ////    }
            ////}

            //foreach (ServiceReference2.EXE ex in allExeList)
            //{
            //    if (ex.Uid == id)
            //    {
            //        foreach (ServiceReference2.gamePlay g in gamePlayList)
            //        {
            //            if (g.StageID == id)
            //            {
            //                gameKey.Add(g.GameKey);
            //            }
            //        }

            //        for (int i = 0; i < cbxYAxis.Items.Count; i++)
            //        {
            //            cbxYAxis.Items.Remove(i);
            //        }

            //        for (int i = 0; i < gameKey.Count; i++)
            //        {
            //            cbxYAxis.Items.Add(gameKey[i]);
            //        }
            //    }
            //}

            ////svc.retrieveSessionOfPatientofExeCompleted += new EventHandler<ServiceReference2.retrieveSessionOfPatientofExeCompletedEventArgs>(svc_retrieveSessionOfPatientofExeCompleted);
            ////svc.retrieveSessionOfPatientofExeAsync(p.Uid, id);

            //gamePlayList.Clear();

            //ArrayList allSessionPatientID = new ArrayList();
            //ArrayList allSessionGameKey = new ArrayList();
            //ArrayList allSessionGameValue = new ArrayList();

            //foreach (ServiceReference2.session s in allSessionOfPatientOfExeList)
            //{
            //    allSessionPatientID.Add(s.SessionID);
            //}

            //foreach (ServiceReference2.gamePlay s in allSessionPatientID)
            //{
            //    allSessionGameKey.Add(s.GameKey);
            //    allSessionGameValue.Add(s.GameValue);
            //}

            ////for (int i = 0; i < gamePlayList.Count(); i++)
            ////{
            ////    if (gamePlayList[i].ExeID != 1)
            ////    {
            ////        gamePlayList.Add(gamePlayList[i]);
            ////    }
            ////}
            ////gamePlayList.Reverse();

            //for (int i = 0; i < allSessionPatientID.Count; i++)
            //{
            //    for (int x = 0; x < allSessionGameKey.Count; i++)
            //    {
            //        DataSeries<double, double> topLeft = new DataSeries<double, double>(allSessionGameKey[x].ToString());
            //        topLeft.Title = allSessionGameKey[x].ToString();

            //        LineSeries ls = new LineSeries();
            //        graph_rangeMotion.Series.Add(ls);
            //        //ls.NormalStyle = 
            //        Style style1 = new System.Windows.Style();
            //        SolidColorBrush red = new SolidColorBrush();
            //        red.Color = Colors.Red;
            //        ls.LineStroke = red;

            //        graph_rangeMotion.Series[0].DataSeries = topLeft;
            //    }
            //}
            //DataSeries<double, double> topLeft = new DataSeries<double, double>("Top Left");
            //DataSeries<double, double> topRight = new DataSeries<double, double>("Top Right");
            //DataSeries<double, double> bottomLeft = new DataSeries<double, double>("Bottom Left");
            //DataSeries<double, double> bottomRight = new DataSeries<double, double>("Bottom Right");
            //topLeft.Title = "Top Left";
            //topRight.Title = "Top Right";
            //bottomRight.Title = "Bottom Right";
            //bottomLeft.Title = "Bottom Left";

            //Add the data points to the data series according to the correct equation
            //for (int i = 0; i < gamePlayList.Count(); i++)
            //{
            //    if (gamePlayList[i] != null && !gamePlayList[i].AvgTime1.Equals(""))
            //    {
            //        topLeft.Add(new DataPoint<double, double>() { X = i, Y = Convert.ToDouble(gamePlayList[i].AvgTime1.ToString()) });
            //        topRight.Add(new DataPoint<double, double>() { X = i, Y = Convert.ToDouble(gamePlayList[i].AvgTime2.ToString()) });
            //        bottomRight.Add(new DataPoint<double, double>() { X = i, Y = Convert.ToDouble(gamePlayList[i].AvgTime3.ToString()) });
            //        bottomLeft.Add(new DataPoint<double, double>() { X = i, Y = Convert.ToDouble(gamePlayList[i].AvgTime4.ToString()) });
            //        topLeft[i].Tag = Convert.ToDouble(gamePlayList[i].AvgTime1.ToString());
            //        topRight[i].Tag = Convert.ToDouble(gamePlayList[i].AvgTime2.ToString());
            //        bottomRight[i].Tag = Convert.ToDouble(gamePlayList[i].AvgTime3.ToString());
            //        bottomLeft[i].Tag = Convert.ToDouble(gamePlayList[i].AvgTime4.ToString());

            //    }
            //}

            //LineSeries ls = new LineSeries();
            //graph_rangeMotion.Series.Add(ls);
            ////ls.NormalStyle = 
            //Style style1 = new System.Windows.Style();
            //SolidColorBrush red = new SolidColorBrush();
            //red.Color = Colors.Red;
            //ls.LineStroke = red;

            //graph_rangeMotion.Series[0].DataSeries = topLeft;
            //graph_rangeMotion.Series[1].DataSeries = topRight;
            //graph_rangeMotion.Series[2].DataSeries = bottomRight;
            //graph_rangeMotion.Series[3].DataSeries = bottomLeft;
            #endregion
            PrintGridMenu.Visibility = Visibility.Visible;
            try
            {
                lsList[0].Visibility = Visibility.Visible;
                lsList.RemoveAt(0);
            }
            catch (Exception) { }
        }

        private void createTable()
        {
            List<string> selectedKeyList = new List<string>();

            DataSet ds = new DataSet();
            DataTable dt = new DataTable();
            ds.Tables.Add(dt);

            DataColumn cl1 = new DataColumn("Session", typeof(string));
            cl1.MaxLength = 100;
            dt.Columns.Add(cl1);

            foreach (CheckBox cbx in cbxYAxis.Items)
            {
                if (cbx.IsChecked == true)
                {
                    selectedKeyList.Add(cbx.Content.ToString());
                    DataColumn cl = new DataColumn(cbx.Content.ToString(), typeof(string));
                    cl.MaxLength = 100;
                    dt.Columns.Add(cl);
                }
            }

            foreach (ServiceReference2.session ps in patientSessionList)
            {
                if (ps.ExeID == selectedExe.Uid)
                {
                    List<ServiceReference2.gamePlay> patientGamePlayList = new List<ServiceReference2.gamePlay>();
                    patientGamePlayList = ps.GamePlaylist;

                    List<string> addedKey = new List<string>();

                    DataRow rw = dt.NewRow();
                    dt.Rows.Add(rw);
                    foreach (ServiceReference2.gamePlay gameplay in patientGamePlayList)
                    {
                        foreach (string key in selectedKeyList)
                        {
                            if (gameplay.GameKey.Equals(key) && (gameplay.StageName.Equals(stageName) || stageName == "nostage"))
                            {
                                if (!addedKey.Contains(gameplay.GameKey))
                                {
                                    addedKey.Add(gameplay.GameKey);
                                    //logic to add it in.

                                    rw[gameplay.GameKey] = gameplay.GameValue.ToString();
                                }
                            }
                        }
                        //if (!gameplayIDlist.Contains(gameplay.Uid))
                        //{
                        //    if (gameKey.Equals(gameplay.GameKey) && (gameplay.StageName.Equals(stageName) || stageName == "nostage"))
                        //    {
                        //        xCount++;
                        //        gameplayIDlist.Add(gameplay.Uid);
                        //    }

                        //}
                    }
                    rw["Session"] = ps.Dateofplay.ToString();
                }
            }
            datagrid1.ItemsSource = ds.Tables[0].DefaultView;
        }

        #endregion

        # region patientList
        #region Variables
        #region static
        private ObservableCollection<patientListItem> patientListItemList = new ObservableCollection<patientListItem>();
        private ObservableCollection<patientListItem2> patientListItem2List = new ObservableCollection<patientListItem2>();
        private ObservableCollection<patientListItem3> patientListItem3List = new ObservableCollection<patientListItem3>();
        private List<patientListItem> patient_own_ListItemList = new List<patientListItem>();
        private List<patientListItem2> patient_own_ListItem2List = new List<patientListItem2>();
        private List<patientListItem3> patient_own_ListItem3List = new List<patientListItem3>();
        private List<patientListItem> patient_oth_ListItemList = new List<patientListItem>();
        private List<patientListItem2> patient_oth_ListItem2List = new List<patientListItem2>();
        private List<patientListItem3> patient_oth_ListItem3List = new List<patientListItem3>();
        #endregion
        int currentPatientListNavigation = 0;
        int currentDetailLevel = 0;
        Storyboard loading1;
        object selectedPatientListItem = new object();
        bool firstTime = false;
        #endregion
        private void lbl_patientList_MouseDoubleClick(object sender, MouseButtonEventArgs e)
        {
            if (((ListBox)sender).SelectedItem != null)
            {
                if (selectPatientMode == true)
                {
                    selectPatientMode = false;
                    //start loading
                    Storyboard loading1;
                    loading1 = (Storyboard)FindResource("selectedPatient");
                    loading1.Begin();
                    menu.Visibility = Visibility.Visible;
                    menu_assessment.Visibility = Visibility.Collapsed;
                }
            }
        }

        private void btn_selectNewPatient_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            if (selectPatientMode == false)
            {
                //stopKinect();
                try
                {
                    nui.Uninitialize();
                }
                catch (Exception)
                {
                }
                panel_kinect.Visibility = Visibility.Collapsed;
                selectPatientMode = true;
                //start loading
                Storyboard loading1;
                loading1 = (Storyboard)FindResource("selectPatient");
                loading1.Begin();
            }
        }

        private void btn_detail_click(object sender, MouseButtonEventArgs e)
        {
            string tag = ((Image)sender).Tag.ToString();
            btn_detail_1.Source = new BitmapImage(new Uri("zoomPoint.png", UriKind.Relative));
            btn_detail_2.Source = new BitmapImage(new Uri("zoomPoint.png", UriKind.Relative));
            btn_detail_3.Source = new BitmapImage(new Uri("zoomPoint.png", UriKind.Relative));

            switch (tag)
            {
                case "in":
                    if (currentDetailLevel == 0)
                    {

                        lbl_patientList.ItemsSource = patientListItem2List;

                        currentDetailLevel++;
                        btn_detail_2.Source = new BitmapImage(new Uri("zoomPointSelected.png", UriKind.Relative));
                    }
                    else if (currentDetailLevel == 1)
                    {

                        lbl_patientList.ItemsSource = patientListItem3List;

                        currentDetailLevel++;
                        btn_detail_3.Source = new BitmapImage(new Uri("zoomPointSelected.png", UriKind.Relative));
                    }
                    else if (currentDetailLevel == 2)
                    {
                        btn_detail_3.Source = new BitmapImage(new Uri("zoomPointSelected.png", UriKind.Relative));
                    }
                    break;
                case "out":
                    if (currentDetailLevel == 2)
                    {

                        lbl_patientList.ItemsSource = patientListItem2List;

                        btn_detail_2.Source = new BitmapImage(new Uri("zoomPointSelected.png", UriKind.Relative));
                        currentDetailLevel--;
                    }
                    else if (currentDetailLevel == 1)
                    {

                        lbl_patientList.ItemsSource = patientListItemList;

                        btn_detail_1.Source = new BitmapImage(new Uri("zoomPointSelected.png", UriKind.Relative));
                        currentDetailLevel--;
                    }
                    else if (currentDetailLevel == 0)
                    {
                        btn_detail_1.Source = new BitmapImage(new Uri("zoomPointSelected.png", UriKind.Relative));
                    }
                    break;
                case "1":
                    if (currentDetailLevel != 0)
                    {

                        lbl_patientList.ItemsSource = patientListItemList;
                        currentDetailLevel = 0;
                        btn_detail_1.Source = new BitmapImage(new Uri("zoomPointSelected.png", UriKind.Relative));
                    }
                    break;
                case "2":
                    if (currentDetailLevel != 1)
                    {

                        lbl_patientList.ItemsSource = patientListItem2List;

                        currentDetailLevel = 1;
                        btn_detail_2.Source = new BitmapImage(new Uri("zoomPointSelected.png", UriKind.Relative));
                    }
                    break;
                case "3":
                    if (currentDetailLevel != 2)
                    {

                        lbl_patientList.ItemsSource = patientListItem3List;

                        btn_detail_3.Source = new BitmapImage(new Uri("zoomPointSelected.png", UriKind.Relative));
                        currentDetailLevel = 2;
                    }
                    break;
                default:
                    break;
            }
        }

        private void btn_detail_1_MouseEnter(object sender, MouseEventArgs e)
        {
            string tag = ((Image)sender).Tag.ToString();

            switch (tag)
            {
                case "1":
                    if (currentDetailLevel != 0)
                    {
                        btn_detail_1.Source = new BitmapImage(new Uri("zoomPointHover.png", UriKind.Relative));
                    }
                    break;
                case "2":
                    if (currentDetailLevel != 1)
                    {
                        btn_detail_2.Source = new BitmapImage(new Uri("zoomPointHover.png", UriKind.Relative));

                    }
                    break;
                case "3":
                    if (currentDetailLevel != 2)
                    {
                        btn_detail_3.Source = new BitmapImage(new Uri("zoomPointHover.png", UriKind.Relative));

                    }

                    break;
                default:
                    break;
            }
        }

        private void btn_detail_1_MouseLeave(object sender, MouseEventArgs e)
        {
            string tag = ((Image)sender).Tag.ToString();

            switch (tag)
            {
                case "1":
                    if (currentDetailLevel != 0)
                    {
                        btn_detail_1.Source = new BitmapImage(new Uri("zoomPoint.png", UriKind.Relative));

                    }
                    break;
                case "2":
                    if (currentDetailLevel != 1)
                    {
                        btn_detail_2.Source = new BitmapImage(new Uri("zoomPoint.png", UriKind.Relative));

                    }
                    break;
                case "3":
                    if (currentDetailLevel != 2)
                    {
                        btn_detail_3.Source = new BitmapImage(new Uri("zoomPoint.png", UriKind.Relative));

                    }

                    break;
                default:
                    break;
            }
        }

        private void preDownloadPatientList()
        {
            patient_own_ListItem2List.Clear();
            patient_own_ListItem3List.Clear();
            patient_oth_ListItem2List.Clear();
            patient_oth_ListItem3List.Clear();

            patient_oth_ListItemList.Clear();
            patient_own_ListItemList.Clear();
            foreach (patient patient in allOwnPatient)
            {
                patientListItem px = new patientListItem(patient, this, allOwnPatient.Count + allOthPatient.Count, true);
                patient_own_ListItemList.Add(px);
            }

            foreach (patient patient in allOthPatient)
            {
                patientListItem px = new patientListItem(patient, this, allOwnPatient.Count + allOthPatient.Count, false);
                patient_oth_ListItemList.Add(px);
            }


        }

        public void preDownloadPart2(patient selectedPatient, List<ServiceReference2.EXE> exeAssignedList, List<ServiceReference2.session> patientSessionList, List<ServiceReference2.problem> problemList, bool myPatient)
        {
            patientListItem2 px2 = new patientListItem2(selectedPatient, exeAssignedList, patientSessionList, problemList);

            patientListItem3 px3 = new patientListItem3(selectedPatient, exeAssignedList, patientSessionList, problemList);
            if (myPatient == true)
            {
                patient_own_ListItem2List.Add(px2);
                patient_own_ListItem3List.Add(px3);
            }
            else
            {
                patient_oth_ListItem2List.Add(px2);
                patient_oth_ListItem3List.Add(px3);
            }
        }

        public void preDownloadPart3()
        {
            //uncommnt later
            grid_selectPatient.Visibility = Visibility.Visible;

            currentDetailLevel = 0;
            currentPatientListNavigation = 0;
            patient_own_ListItem3List.Sort(delegate(patientListItem3 p1, patientListItem3 p2) { return p1.selectedPatient.Uid.CompareTo(p2.selectedPatient.Uid); });

            btn_otherPatient_MouseLeftButtonDown(btn_myPatient, null);
            Image image = new Image();
            image.Tag = "3";

            btn_detail_click(image, null);
        }

        public void startLoading()
        {
            gridLoading.Visibility = Visibility.Visible;
            //start loading
            loading1 = (Storyboard)FindResource("loading");
            loading1.RepeatBehavior = RepeatBehavior.Forever;
            loading1.Begin();
        }

        public void stopLoading()
        {
            gridLoading.Visibility = Visibility.Collapsed;
            loading1.Stop();
        }

        private void btn_otherPatient_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {

            string tag = ((TextBlock)sender).Tag.ToString();

            BrushConverter brush = new BrushConverter();
            btn_myPatientB.Background = (Brush)brush.ConvertFromString("#FF3A3A3A");
            btn_otherPatientB.Background = (Brush)brush.ConvertFromString("#FF3A3A3A");
            btn_myPatient.Foreground = (Brush)brush.ConvertFromString("#FFFFFFFF");
            btn_otherPatient.Foreground = (Brush)brush.ConvertFromString("#FFFFFFFF");
            btn_otherPatient.Height = 26;
            btn_myPatient.Height = 26;
            patientListItemList.Clear();
            patientListItem2List.Clear();
            patientListItem3List.Clear();

            switch (tag)
            {
                case "0":

                    BrushConverter brush1 = new BrushConverter();
                    btn_myPatientB.Background = (Brush)brush1.ConvertFromString("#FFFFFFFF");
                    //BitmapImage test1 = new BitmapImage(new Uri("KS_myPatientBG.png", UriKind.Relative));
                    //ImageBrush brush3 = new ImageBrush();
                    //brush3.ImageSource = test1;
                    //btn_myPatientB.Background = brush3;
                    btn_myPatient.Foreground = (Brush)brush1.ConvertFromString("#FF000000");
                    btn_myPatient.Height = 30;
                    foreach (patientListItem temp in patient_own_ListItemList)
                    {
                        patientListItemList.Add(temp);
                    }
                    foreach (patientListItem2 temp in patient_own_ListItem2List)
                    {
                        patientListItem2List.Add(temp);
                    }
                    foreach (patientListItem3 temp in patient_own_ListItem3List)
                    {
                        patientListItem3List.Add(temp);
                    }

                    if (currentDetailLevel == 0)
                    {
                        lbl_patientList.ItemsSource = patientListItemList;
                    }
                    else if (currentDetailLevel == 1)
                    {
                        lbl_patientList.ItemsSource = patientListItem2List;
                    }
                    else if (currentDetailLevel == 2)
                    {
                        lbl_patientList.ItemsSource = patientListItem3List;
                    }


                    currentPatientListNavigation = 0;

                    break;
                case "1":
                    BrushConverter brush2 = new BrushConverter();
                    btn_otherPatientB.Background = (Brush)brush2.ConvertFromString("#FFFFFFFF");
                    //BitmapImage test = new BitmapImage(new Uri("KS_otherPatientBG.png", UriKind.Relative));
                    //ImageBrush brush4 = new ImageBrush();
                    //brush4.ImageSource = test;
                    //btn_otherPatientB.Background = brush4;
                    btn_otherPatient.Foreground = (Brush)brush2.ConvertFromString("#FF000000");
                    btn_otherPatient.Height = 30;
                    foreach (patientListItem temp in patient_oth_ListItemList)
                    {
                        patientListItemList.Add(temp);
                    }
                    foreach (patientListItem2 temp in patient_oth_ListItem2List)
                    {
                        patientListItem2List.Add(temp);
                    }
                    foreach (patientListItem3 temp in patient_oth_ListItem3List)
                    {
                        patientListItem3List.Add(temp);
                    }

                    if (currentDetailLevel == 0)
                    {
                        lbl_patientList.ItemsSource = patientListItemList;
                    }
                    else if (currentDetailLevel == 1)
                    {
                        lbl_patientList.ItemsSource = patientListItem2List;
                    }
                    else if (currentDetailLevel == 2)
                    {
                        lbl_patientList.ItemsSource = patientListItem3List;
                    }

                    currentPatientListNavigation = 1;

                    break;
                default:
                    break;
            }
        }

        private void lbl_patientList_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (firstTime == false)
            {
                patientBanner.Visibility = Visibility.Visible;
                sp_assessment.Visibility = Visibility.Visible;
            }


            firstTime = true;
            resetProblemTag();
            bool error = false;
            patient selectedPatient = new patient();
            if (currentDetailLevel == 0)
            {
                try
                {
                    selectedPatientListItem = (patientListItem)lbl_patientList.SelectedItem;
                    selectedPatient = ((patientListItem)lbl_patientList.SelectedItem).selectedPatient;
                    exeAssignedList = ((patientListItem)lbl_patientList.SelectedItem).exeAssignedList;

                    // retrieve all treatment analysis data
                    patientSessionList = ((patientListItem)lbl_patientList.SelectedItem).patientSessionList;

                    //retrieve problems that the patient have
                    problemList = ((patientListItem)lbl_patientList.SelectedItem).problemList;

                }
                catch (Exception) { error = true; }

            }
            else if (currentDetailLevel == 1)
            {
                try
                {
                    selectedPatientListItem = (patientListItem2)lbl_patientList.SelectedItem;
                    selectedPatient = ((patientListItem2)lbl_patientList.SelectedItem).selectedPatient;
                    exeAssignedList = ((patientListItem2)lbl_patientList.SelectedItem).exeAssignedList;

                    // retrieve all treatment analysis data
                    patientSessionList = ((patientListItem2)lbl_patientList.SelectedItem).patientSessionList;

                    //retrieve problems that the patient have
                    problemList = ((patientListItem2)lbl_patientList.SelectedItem).problemList;
                }
                catch (Exception) { error = true; }

            }
            else if (currentDetailLevel == 2)
            {
                try
                {
                    selectedPatientListItem = (patientListItem3)lbl_patientList.SelectedItem;
                    selectedPatient = ((patientListItem3)lbl_patientList.SelectedItem).selectedPatient;
                    exeAssignedList = ((patientListItem3)lbl_patientList.SelectedItem).exeAssignedList;
                    
                    // retrieve all treatment analysis data
                    patientSessionList = ((patientListItem3)lbl_patientList.SelectedItem).patientSessionList;

                    //retrieve problems that the patient have
                    problemList = ((patientListItem3)lbl_patientList.SelectedItem).problemList;

                    lbl_admission.Text = selectedPatient.Admission;
                    lbl_assessment.Text = selectedPatient.Assessment;
                    lbl_OTnotes.Text = selectedPatient.OTNotes1;
                    lbl_latestGameplay.Text = selectedPatient.Latestgameplay;
                }
                catch (Exception) { error = true; }

            }
            if (error == false)
            {
                doWorkAfterPatientSelected(selectedPatient);
                clearData();
            }
        }

        private void clearData()
        {
            cbxTreatment.SelectedIndex = -1;
            cbxPerformance.SelectedIndex = -1;
            cbxYAxis.SelectedIndex = -1;

            cbxTreatment.ItemsSource = null;
            sp_Stage.Visibility = Visibility.Collapsed;
            sp_Attribute.Visibility = Visibility.Collapsed;
            stageName = "";
            selectedExe = null;
            //lbx_exe.Items.Clear();
            //lbx_exeAssigned.Items.Clear();

            tbx_joint_Copy.Text = "";
            tbx_joint.Text = "Unselected";

            //tbxReport.Text = "";
            //tbxReport.Text = "";
            //tbxNote.Text = "";

            lblSever.Text = "";
            // set the color for severity
            int severity = 0;
            pbrSever.Value = (severity * 20);
            if (pbrSever.Value >= 60)
            {
                pbrSever.Foreground = Brushes.Red;
            }
            else if (pbrSever.Value < 60 && pbrSever.Value >= 20)
            {
                pbrSever.Foreground = Brushes.Yellow;
            }
            else
            {
                pbrSever.Foreground = Brushes.DarkGreen;
            }
        }
        #endregion

        private void lblSever_LostFocus(object sender, RoutedEventArgs e)
        {
            // set the color for severity
            int severity = 0;
            try
            {
                severity = Convert.ToInt16(lblSever.Text);
                severity = 6 - severity;
            }
            catch (Exception)
            {
                MessageBox.Show("Please enter 1 - 5 for severity");
            }
            if (severity < 0 || severity > 5)
            {
                MessageBox.Show("Please enter 1 - 5 for severity");
            }
            else
            {
                pbrSever.Value = (severity * 20);
                if (pbrSever.Value >= 60)
                {
                    pbrSever.Foreground = Brushes.Red;
                }
                else if (pbrSever.Value < 60 && pbrSever.Value >= 20)
                {
                    pbrSever.Foreground = Brushes.Yellow;
                }
                else
                {
                    pbrSever.Foreground = Brushes.DarkGreen;
                }
            }
        }

        private void tbx_table_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            panel_graph.Visibility = Visibility.Collapsed;
            panel_table.Visibility = Visibility.Visible;
            //createTable();
        }

        #region event handlers

        #region application closing..


        bool logout = false;

        private void btn_logout_MouseLeftButtonUp(object sender, System.Windows.Input.MouseButtonEventArgs e)
        {
            MainWindow win = new MainWindow();
            logout = true;
            this.Hide();
            win.Show();
            if (BWstarted == true)
            {
                //stopKinect();
                try
                {
                    nui.Uninitialize();
                }
                catch (Exception)
                {
                }
            }
        }

        private void Window_Closing(object sender, CancelEventArgs e)
        {
            try
            {
                if (logout == false)
                {
                    //stopKinect();
                    try
                    {
                        nui.Uninitialize();
                    }
                    catch (Exception)
                    {
                    }
                    Application.Current.Shutdown();

                }
            }
            catch (Exception) { }
        }

        private void Window_Closed(object sender, EventArgs e)
        {
            try
            {
                //if (logout == false)
                //{
                //stopKinect();
                nui.Uninitialize();
                //Application.Current.Shutdown();
                //}
            }
            catch (Exception) { }
            try
            {
                if (logout == false)
                {
                    //stopKinect();
                    //nui.Uninitialize();
                    Application.Current.Shutdown();
                }
            }
            catch
            {

            }
        }

        #endregion

        private void tbx_graph_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            panel_graph.Visibility = Visibility.Visible;
            panel_table.Visibility = Visibility.Collapsed;
            //createChart();
        }
        bool spShow = false;
        private void Window_KeyDown(object sender, KeyEventArgs e)
        {
           
            if (e.Key == Key.F12)
            {
                try
                {
                    //redownload data
                    patientSessionList = svc.retrieveSessionOfPatient(p.Uid);
                    svc.retrieveExeAssignedtoPatientCompleted += new EventHandler<ServiceReference2.retrieveExeAssignedtoPatientCompletedEventArgs>(svc_retrieveExeAssignedtoPatientCompleted);
                    svc.retrieveExeAssignedtoPatientAsync(p.Uid);
                    svc.retrievePatientProblemsCompleted += new EventHandler<ServiceReference2.retrievePatientProblemsCompletedEventArgs>(svc_retrievePatientProblemsCompleted);
                    svc.retrievePatientProblemsAsync(p.Uid);
                }
                catch (Exception) { }
            }
            else if (e.Key == Key.F11 || e.SystemKey == Key.F11)
            {
                try
                {
                    if (showJointLabel)
                    {
                        lblLeftElbow.Visibility = Visibility.Collapsed;
                    }
                    else
                    {
                        lblLeftElbow.Visibility = Visibility.Visible;
                    }
                    showJointLabel = !showJointLabel;
                }
                catch (NullReferenceException ex)
                { }
            }
            else if (e.Key == Key.F10 || e.SystemKey == Key.F10)
            {
                if (spShow == false)
                {
                    spAngle0.Visibility = Visibility.Collapsed;
                    spAngle.Visibility = Visibility.Visible;
                    sp_severity.Visibility = Visibility.Visible;
                    spShow = true;
                }
                //else
                //{
                //    spAngle.Visibility = Visibility.Collapsed;
                //    spAngle0.Visibility = Visibility.Visible;
                //    spShow = false;
                //}
            }
            else if (e.Key == Key.F9 || e.SystemKey == Key.F9)
            {
                try
                {
                    lsList[0].Visibility = Visibility.Visible;
                    lsList.RemoveAt(0);
                }
                catch (Exception)
                {

                }
            }
            else if (e.Key == Key.F2 || e.SystemKey == Key.F2)
            {
                try
                {
                    toSave = true;
                }
                catch (Exception)
                {

                }
            }
        }
        private List<LineSeries> lsList = new List<LineSeries>();
        bool menuOpen = false;

        private void btn_menu_MouseLeftButtonDown(object sender, System.Windows.Input.MouseButtonEventArgs e)
        {
            if (menuOpen == false)
            {
                menuOpen = true;
                grid_menu_show.Visibility = Visibility.Visible;
                //grid_menu_show.Focus();
                //this.Focus();
                //img_menuBG.Focusable = true;
                //bool result = img_menuBG.Focus();
            }
            else
            {
                menuOpen = false;
                grid_menu_show.Visibility = Visibility.Collapsed;

            }

        }

        private void Grid_MouseLeftButtonDown(object sender, System.Windows.Input.MouseButtonEventArgs e)
        {
            menuOpen = false;
            grid_menu_show.Visibility = Visibility.Collapsed;
        }

        #region menu
        private void TextBlock_MouseLeftButtonDown(object sender, System.Windows.Input.MouseButtonEventArgs e)
        {
            string clickedTag = ((TextBlock)sender).Tag.ToString();

            switch (clickedTag)
            {
                case "1":
                    grid_menu_show.Visibility = Visibility.Collapsed;
                    selectedtreatment = "Fugl Meyer";
                    currentSessionID = 0;
                    fuglMeyer.Visibility = Visibility.Visible;
                    datagrid2.Visibility = Visibility.Collapsed;
                    sp_k_startROM.Visibility = Visibility.Collapsed;
                    #region Fugl Meyer

                    beforetbx_joint = tbx_joint.Text;
                    beforetbx_joint_copy = tbx_joint_Copy.Text;
                    startShowed = false;

                    //panel_calibrate.Visibility = Visibility.Visible;
                    panel_kinect.Visibility = Visibility.Visible;
                    //skeleton.Children.Clear();
                    maxActive = 0;
                    maxPassive = 0;
                    minActive = 0;
                    minPassive = 0;
                    sp_k_stage.Visibility = Visibility.Collapsed;
                    sp_k_field.Visibility = Visibility.Collapsed;
                    btn_proceed.IsEnabled = true;
                    btn_start.IsEnabled = true;
                    gotUser = false;
                    sp_k_controlPanel.Visibility = Visibility.Collapsed;
                    sp_k_controlPanel_start.Visibility = Visibility.Collapsed;
                    lbl_k_jointName.Text = tbx_joint.Text;
                    checkbx_passive.IsChecked = true;
                    //initalizeAndstartKinect();
                                        skeleton.Visibility = Visibility.Visible;
                    //panel_calibrate.Visibility = Visibility.Collapsed;
                    initalizeStartKinectSDK();

                    #endregion
                    break;
                case "2":
                    grid_menu_show.Visibility = Visibility.Collapsed;
                    selectedtreatment = "Joint ROM";
                    allowedROMtoStart = false;
                    savingROMresult = false;
                    startShowed = false;
                    datagrid2.ItemsSource = null;
                    fuglMeyer.Visibility = Visibility.Collapsed;
                    datagrid2.Visibility = Visibility.Collapsed;
                    sp_k_startROM.Visibility = Visibility.Visible;
                    //panel_calibrate.Visibility = Visibility.Visible;
                    panel_kinect.Visibility = Visibility.Visible;
                    //gotUser = false;
                    //initalizeAndstartKinect();
                    skeleton.Visibility = Visibility.Visible;
                    //panel_calibrate.Visibility = Visibility.Collapsed;
                    initalizeStartKinectSDK();
                    #region resetData

                    //maxJoint1 = 0;
                    maxJoint2 = 0;
                    maxJoint3 = 0;
                    maxJoint4 = 0;
                    maxJoint5 = 0;
                    //maxJoint6 = 0;
                    //maxJoint7 = 0;
                    maxJoint8 = 0;
                    maxJoint9 = 0;
                    maxJoint10 = 0;
                    maxJoint11 = 0;
                    maxJoint12 = 0;
                    //maxJoint13 = 0;
                    //maxJoint14 = 0;
                    //minJoint1 = 0;
                    minJoint2 = 0;
                    minJoint3 = 0;
                    minJoint4 = 0;
                    minJoint5 = 0;
                    //minJoint6 = 0;
                    //minJoint7 = 0;
                    minJoint8 = 0;
                    minJoint9 = 0;
                    minJoint10 = 0;
                    minJoint11 = 0;
                    minJoint12 = 0;
                    //minJoint13 = 0;
                    //minJoint14 = 0;

                    #endregion

                    ds = new DataSet();
                    dt = new DataTable();
                    ds.Tables.Add(dt);

                    DataColumn cl = new DataColumn("Joint", typeof(string));
                    cl.MaxLength = 100;
                    dt.Columns.Add(cl);

                    cl = new DataColumn("Max Angle", typeof(string));
                    cl.MaxLength = 100;
                    dt.Columns.Add(cl);

                    cl = new DataColumn("Min Angle", typeof(string));
                    cl.MaxLength = 100;
                    dt.Columns.Add(cl);

                    break;
                case "3":
                    btn_selectNewPatient_MouseLeftButtonDown(btn_selectNewPatient, null);
                    grid_menu_show.Visibility = Visibility.Collapsed;
                    break;
                case "5":
                    btn_test_Click(sender, e);
                    break;
                default:
                    break;
            }
        }

        private void TextBlock_MouseEnter(object sender, System.Windows.Input.MouseEventArgs e)
        {
            BrushConverter brush = new BrushConverter();
            ((TextBlock)sender).Background = (Brush)brush.ConvertFromString("#FF249D36");
        }

        private void TextBlock_MouseLeave(object sender, System.Windows.Input.MouseEventArgs e)
        {
            BrushConverter brush = new BrushConverter();
            ((TextBlock)sender).Background = (Brush)brush.ConvertFromString("#FF3598AE");
        }


        #endregion

        private void btn_test_Click(object sender, System.Windows.RoutedEventArgs e)
        {
            ToPrint tp = new ToPrint();
            tp.img_patient.Source = this.img_patient.Source;
            tp.nameLabel1.Title = this.nameLabel1.Title;
            tp.nameLabel1.GivenName = this.nameLabel1.GivenName;
            tp.nameLabel1.FamilyName = this.nameLabel1.FamilyName;
            tp.addressLabel1.Address1 = this.addressLabel1.Address1;
            tp.addressLabel1.Address2 = this.addressLabel1.Address2;
            tp.addressLabel1.Country = this.addressLabel1.Country;
            tp.IdentifierValue.Text = this.IdentifierValue.Text;
            tp.DOBValue.Text = this.DOBValue.Text;
            tp.GenderValue.Text = this.GenderValue.Text;
            tp.home.Text = this.home.Text;
            tp.mobile.Text = this.mobile.Text;
            tp.email.Text = this.email.Text;
            tp.lbl_eName.Text = this.lbl_eName.Text;
            tp.lbl_eRelationship.Text = this.lbl_eRelationship.Text;
            tp.addressLabel2.Address1 = this.addressLabel2.Address1;
            tp.addressLabel2.Address2 = this.addressLabel2.Address2;
            tp.addressLabel2.Country = this.addressLabel2.Country;
            foreach (String cbx in cbxTreatment.Items)
            {
                tp.cbxTreatment.Items.Add(cbx);
            }
            tp.cbxTreatment.SelectedIndex = this.cbxTreatment.SelectedIndex;
            foreach (String cbx in cbxPerformance.Items)
            {
                tp.cbxPerformance.Items.Add(cbx);
            }
            tp.cbxPerformance.SelectedIndex = this.cbxPerformance.SelectedIndex;

            #region createchart
            gotRange = false;
            colorCount = 0;
            tp.graph_rangeMotion.Series.Clear();
            Visiblox.Charts.DateTimeAxis asd = new DateTimeAxis();
            tp.graph_rangeMotion.XAxis = asd;
            bool title = false;
            List<string> selectedKeyList = new List<string>();

            #region check for selected items

            foreach (CheckBox cbx in cbxYAxis.Items)
            {
                if (cbx.IsChecked == true)
                {
                    if (!cbx.Content.ToString().Contains("Range"))
                    {
                        selectedKeyList.Add(cbx.Content.ToString());
                    }
                    else
                    {
                        gotRange = true;
                    }
                }
            }
            #endregion

            #region noRange
            int keyCount = 0;
            for (int i1 = 0; i1 < selectedKeyList.Count; i1++)
            {
                string gameKey = selectedKeyList[i1];
                int count = 0;

                DataSeries<DateTime, double> temp = new DataSeries<DateTime, double>(gameKey);
                int xCount = 0;
                foreach (ServiceReference2.session ps in patientSessionList)
                {
                    if (ps.ExeID == selectedExe.Uid)
                    {
                        List<ServiceReference2.gamePlay> patientGamePlayList = new List<ServiceReference2.gamePlay>();
                        patientGamePlayList = ps.GamePlaylist;

                        List<int> gameplayIDlist = new List<int>();

                        foreach (ServiceReference2.gamePlay gameplay in patientGamePlayList)
                        {
                            if (!gameplayIDlist.Contains(gameplay.Uid))
                            {
                                //if (gameKey.Equals(gameplay.GameKey) && (gameplay.StageName.Equals(stageName) || stageName == "nostage"))
                                if (gameKey.Equals(gameplay.GameKey) && (gameplay.StageName.Equals(stageName) || gameplay.StageName.Equals("nostage")))
                                {
                                    xCount++;
                                    gameplayIDlist.Add(gameplay.Uid);
                                }

                            }
                        }
                    }
                }

                DateTime[] x = new DateTime[xCount];
                double[] y = new double[xCount];

                foreach (ServiceReference2.session patientSession in patientSessionList)
                {
                    string notes = "";
                    if (patientSession.ExeID == selectedExe.Uid)
                    {
                        List<ServiceReference2.gamePlay> patientGamePlayList = new List<ServiceReference2.gamePlay>();
                        patientGamePlayList = patientSession.GamePlaylist;

                        List<int> gameplayIDlist = new List<int>();

                        foreach (ServiceReference2.gamePlay gameplay in patientGamePlayList)
                        {
                            if (!gameplayIDlist.Contains(gameplay.Uid))
                            {
                                if (gameKey.Equals(gameplay.GameKey) && (gameplay.StageName.Equals(stageName) || stageName == "nostage"))
                                {
                                    gameplayIDlist.Add(gameplay.Uid);
                                    x[count] = patientSession.Dateofplay;
                                    y[count] = Convert.ToDouble(gameplay.GameValue);
                                    count++;
                                    if (gameplay.SpecialInstructions != "")
                                    {
                                        try
                                        {
                                            notes += svc.retrieveJointName(gameplay.Joint) + " : " + gameplay.SpecialInstructions + ";";
                                        }
                                        catch (Exception)
                                        {
                                            notes += gameplay.Joint + " : " + gameplay.SpecialInstructions + ";";
                                        }
                                    }

                                    if (title == false)
                                    {
                                        TextBlock textblock = new TextBlock();
                                        SolidColorBrush color = new SolidColorBrush();
                                        color.Color = Colors.White;
                                        textblock.Foreground = color;
                                        textblock.Text = "Notes";
                                        textblock.FontWeight = FontWeights.Bold;
                                        textblock.Margin = new Thickness(0, 5, 0, 5);
                                        title = true;
                                    }


                                }
                            }
                        }
                    }
                    keyCount++;
                }
                for (int i = 0; i < x.Length; i++)
                {
                    temp.Add(new DataPoint<DateTime, double>() { X = x[i], Y = y[i] });
                }
                LineSeries ls = new LineSeries();

                SolidColorBrush color1 = new SolidColorBrush();
                color1.Color = colurList[colorCount];
                ls.LineStroke = color1;
                colorCount++;
                ls.LineStrokeThickness = 4;

                tp.graph_rangeMotion.Series.Add(ls);


                tp.graph_rangeMotion.Series[i1].DataSeries = temp;
            }

            #endregion

            #region gotRange
            bool showLegendRange = false;
            if (gotRange == true)
            {
                foreach (ServiceReference2.session patientSession in patientSessionList)
                {
                    DataSeries<DateTime, double> temp = new DataSeries<DateTime, double>("Range");
                    DateTime[] x = new DateTime[2];
                    double[] y = new double[2];
                    double gameValue1 = 0.0;
                    double gameValue2 = 0.0;
                    if (patientSession.ExeID == selectedExe.Uid)
                    {
                        List<ServiceReference2.gamePlay> patientGamePlayList = new List<ServiceReference2.gamePlay>();
                        patientGamePlayList = patientSession.GamePlaylist;

                        foreach (ServiceReference2.gamePlay gameplay in patientGamePlayList)
                        {
                            if (gameplay.GameKey.Contains("Angle") && (gameplay.StageName.Equals(stageName) || stageName == "nostage"))
                            {
                                if (gameValue1 == 0.0)
                                {
                                    try
                                    {
                                        gameValue1 = Convert.ToDouble(gameplay.GameValue);
                                        x[0] = patientSession.Dateofplay;
                                        y[0] = gameValue1;
                                        temp.Add(new DataPoint<DateTime, double>() { X = x[0], Y = y[0] });
                                    }
                                    catch (Exception) { }
                                }
                                else
                                {
                                    try
                                    {
                                        gameValue2 = Convert.ToDouble(gameplay.GameValue);
                                        x[1] = patientSession.Dateofplay;
                                        y[1] = gameValue2;
                                        temp.Add(new DataPoint<DateTime, double>() { X = x[1], Y = y[1] });
                                    }
                                    catch (Exception) { }
                                }
                            }
                        }

                        LineSeries ls = new LineSeries();

                        SolidColorBrush color1 = new SolidColorBrush();
                        color1.Color = Colors.Red;
                        ls.LineStroke = color1;
                        colorCount++;
                        ls.LineStrokeThickness = 4;
                        ls.DataSeries = temp;
                        if (showLegendRange == false)
                        {
                            showLegendRange = true;
                        }
                        else
                            ls.IsDisplayedOnLegend = false;
                        tp.graph_rangeMotion.Series.Add(ls);

                    }

                }
            }

            #endregion

            #region unwanted
            //ArrayList gameKey = new ArrayList();
            //string performance = "";
            //cbxYAxis.Visibility = Visibility.Visible;
            //if (cbxPerformance.Visibility == Visibility.Collapsed)
            //{
            //}
            //else
            //{
            //    performance = cbxPerformance.SelectedItem.ToString();
            //}


            ////foreach (ServiceReference2.stage s in stageList)
            ////{
            ////    if (performance.Equals(s.Name))
            ////    {
            ////        id = s.Uid;
            ////        svc.retrieveSessionOfPatientofExeCompleted += new EventHandler<ServiceReference2.retrieveSessionOfPatientofExeCompletedEventArgs>(svc_retrieveSessionOfPatientofExeCompleted);
            ////        svc.retrieveSessionOfPatientofExeAsync(p.Uid, id);
            ////    }
            ////}

            //foreach (ServiceReference2.EXE ex in allExeList)
            //{
            //    if (ex.Uid == id)
            //    {
            //        foreach (ServiceReference2.gamePlay g in gamePlayList)
            //        {
            //            if (g.StageID == id)
            //            {
            //                gameKey.Add(g.GameKey);
            //            }
            //        }

            //        for (int i = 0; i < cbxYAxis.Items.Count; i++)
            //        {
            //            cbxYAxis.Items.Remove(i);
            //        }

            //        for (int i = 0; i < gameKey.Count; i++)
            //        {
            //            cbxYAxis.Items.Add(gameKey[i]);
            //        }
            //    }
            //}

            ////svc.retrieveSessionOfPatientofExeCompleted += new EventHandler<ServiceReference2.retrieveSessionOfPatientofExeCompletedEventArgs>(svc_retrieveSessionOfPatientofExeCompleted);
            ////svc.retrieveSessionOfPatientofExeAsync(p.Uid, id);

            //gamePlayList.Clear();

            //ArrayList allSessionPatientID = new ArrayList();
            //ArrayList allSessionGameKey = new ArrayList();
            //ArrayList allSessionGameValue = new ArrayList();

            //foreach (ServiceReference2.session s in allSessionOfPatientOfExeList)
            //{
            //    allSessionPatientID.Add(s.SessionID);
            //}

            //foreach (ServiceReference2.gamePlay s in allSessionPatientID)
            //{
            //    allSessionGameKey.Add(s.GameKey);
            //    allSessionGameValue.Add(s.GameValue);
            //}

            ////for (int i = 0; i < gamePlayList.Count(); i++)
            ////{
            ////    if (gamePlayList[i].ExeID != 1)
            ////    {
            ////        gamePlayList.Add(gamePlayList[i]);
            ////    }
            ////}
            ////gamePlayList.Reverse();

            //for (int i = 0; i < allSessionPatientID.Count; i++)
            //{
            //    for (int x = 0; x < allSessionGameKey.Count; i++)
            //    {
            //        DataSeries<double, double> topLeft = new DataSeries<double, double>(allSessionGameKey[x].ToString());
            //        topLeft.Title = allSessionGameKey[x].ToString();

            //        LineSeries ls = new LineSeries();
            //        graph_rangeMotion.Series.Add(ls);
            //        //ls.NormalStyle = 
            //        Style style1 = new System.Windows.Style();
            //        SolidColorBrush red = new SolidColorBrush();
            //        red.Color = Colors.Red;
            //        ls.LineStroke = red;

            //        graph_rangeMotion.Series[0].DataSeries = topLeft;
            //    }
            //}
            //DataSeries<double, double> topLeft = new DataSeries<double, double>("Top Left");
            //DataSeries<double, double> topRight = new DataSeries<double, double>("Top Right");
            //DataSeries<double, double> bottomLeft = new DataSeries<double, double>("Bottom Left");
            //DataSeries<double, double> bottomRight = new DataSeries<double, double>("Bottom Right");
            //topLeft.Title = "Top Left";
            //topRight.Title = "Top Right";
            //bottomRight.Title = "Bottom Right";
            //bottomLeft.Title = "Bottom Left";

            //Add the data points to the data series according to the correct equation
            //for (int i = 0; i < gamePlayList.Count(); i++)
            //{
            //    if (gamePlayList[i] != null && !gamePlayList[i].AvgTime1.Equals(""))
            //    {
            //        topLeft.Add(new DataPoint<double, double>() { X = i, Y = Convert.ToDouble(gamePlayList[i].AvgTime1.ToString()) });
            //        topRight.Add(new DataPoint<double, double>() { X = i, Y = Convert.ToDouble(gamePlayList[i].AvgTime2.ToString()) });
            //        bottomRight.Add(new DataPoint<double, double>() { X = i, Y = Convert.ToDouble(gamePlayList[i].AvgTime3.ToString()) });
            //        bottomLeft.Add(new DataPoint<double, double>() { X = i, Y = Convert.ToDouble(gamePlayList[i].AvgTime4.ToString()) });
            //        topLeft[i].Tag = Convert.ToDouble(gamePlayList[i].AvgTime1.ToString());
            //        topRight[i].Tag = Convert.ToDouble(gamePlayList[i].AvgTime2.ToString());
            //        bottomRight[i].Tag = Convert.ToDouble(gamePlayList[i].AvgTime3.ToString());
            //        bottomLeft[i].Tag = Convert.ToDouble(gamePlayList[i].AvgTime4.ToString());

            //    }
            //}

            //LineSeries ls = new LineSeries();
            //graph_rangeMotion.Series.Add(ls);
            ////ls.NormalStyle = 
            //Style style1 = new System.Windows.Style();
            //SolidColorBrush red = new SolidColorBrush();
            //red.Color = Colors.Red;
            //ls.LineStroke = red;

            //graph_rangeMotion.Series[0].DataSeries = topLeft;
            //graph_rangeMotion.Series[1].DataSeries = topRight;
            //graph_rangeMotion.Series[2].DataSeries = bottomRight;
            //graph_rangeMotion.Series[3].DataSeries = bottomLeft;
            #endregion
            //PrintGridMenu.Visibility = Visibility.Visible;
            #endregion

            #region createChart unwanted

            //panel_moreInformation.Children.Clear();
            //colorCount = 0;
            //tp.graph_rangeMotion.Series.Clear();
            //Visiblox.Charts.DateTimeAxis asd = new DateTimeAxis();
            //tp.graph_rangeMotion.XAxis = asd;
            //bool title = false;
            //List<string> selectedKeyList = new List<string>();
            //foreach (CheckBox cbx in cbxYAxis.Items)
            //{
            //    if (cbx.IsChecked == true)
            //    {
            //        selectedKeyList.Add(cbx.Content.ToString());
            //    }
            //}
            ////datagrid1.Columns.Clear();
            ////datagrid1.Items.Clear();
            ////DataGridTextColumn column = new DataGridTextColumn();
            ////column.Header = "Session";
            ////datagrid1.Columns.Add(column);
            //int keyCount = 0;
            //for (int i1 = 0; i1 < selectedKeyList.Count; i1++)
            //{
            //    string gameKey = selectedKeyList[i1];
            //    int count = 0;

            //    //DataGridTextColumn column1 = new DataGridTextColumn();
            //    //column.Header = gameKey;
            //    //datagrid1.Columns.Add(column);

            //    DataSeries<DateTime, double> temp = new DataSeries<DateTime, double>(gameKey);
            //    int xCount = 0;
            //    foreach (ServiceReference2.session ps in patientSessionList)
            //    {

            //        if (ps.ExeID == selectedExe.Uid)
            //        {
            //            List<ServiceReference2.gamePlay> patientGamePlayList = new List<ServiceReference2.gamePlay>();
            //            patientGamePlayList = ps.GamePlaylist;

            //            List<int> gameplayIDlist = new List<int>();


            //            foreach (ServiceReference2.gamePlay gameplay in patientGamePlayList)
            //            {
            //                if (!gameplayIDlist.Contains(gameplay.Uid))
            //                {
            //                    //if (gameKey.Equals(gameplay.GameKey) && (gameplay.StageName.Equals(stageName) || stageName == "nostage"))
            //                    if (gameKey.Equals(gameplay.GameKey) && (gameplay.StageName.Equals(stageName) || gameplay.StageName.Equals("nostage")))
            //                    {
            //                        xCount++;
            //                        gameplayIDlist.Add(gameplay.Uid);
            //                    }

            //                }
            //            }

            //        }
            //    }
            //    DateTime[] x = new DateTime[xCount];
            //    double[] y = new double[xCount];

            //    foreach (ServiceReference2.session patientSession in patientSessionList)
            //    {
            //        string notes = "";
            //        if (patientSession.ExeID == selectedExe.Uid)
            //        {
            //            List<ServiceReference2.gamePlay> patientGamePlayList = new List<ServiceReference2.gamePlay>();
            //            patientGamePlayList = patientSession.GamePlaylist;

            //            List<int> gameplayIDlist = new List<int>();



            //            foreach (ServiceReference2.gamePlay gameplay in patientGamePlayList)
            //            {
            //                if (!gameplayIDlist.Contains(gameplay.Uid))
            //                {
            //                    if (gameKey.Equals(gameplay.GameKey) && (gameplay.StageName.Equals(stageName) || stageName == "nostage"))
            //                    {
            //                        gameplayIDlist.Add(gameplay.Uid);
            //                        x[count] = patientSession.Dateofplay;
            //                        y[count] = Convert.ToDouble(gameplay.GameValue);
            //                        count++;
            //                        if (gameplay.SpecialInstructions != "")
            //                        {
            //                            try
            //                            {
            //                                notes += svc.retrieveJointName(gameplay.Joint) + " : " + gameplay.SpecialInstructions + ";";
            //                            }
            //                            catch (Exception)
            //                            {
            //                                notes += gameplay.Joint + " : " + gameplay.SpecialInstructions + ";";
            //                            }
            //                        }

            //                        if (title == false)
            //                        {
            //                            TextBlock textblock = new TextBlock();
            //                            SolidColorBrush color = new SolidColorBrush();
            //                            color.Color = Colors.White;
            //                            textblock.Foreground = color;
            //                            textblock.Text = "Notes";
            //                            textblock.FontWeight = FontWeights.Bold;
            //                            textblock.Margin = new Thickness(0, 5, 0, 5);
            //                            panel_moreInformation.Children.Add(textblock);
            //                            title = true;
            //                        }

            //                        #region more information logic
            //                        if (keyCount < patientSessionList.Count && count <= patientSessionList.Count)
            //                        {
            //                            TextBlock textblock = new TextBlock();
            //                            SolidColorBrush color = new SolidColorBrush();
            //                            color.Color = Colors.White;
            //                            textblock.Foreground = color;
            //                            textblock.Text = "Session : " + patientSession.Dateofplay;
            //                            textblock.Margin = new Thickness(0, 5, 0, 5);
            //                            panel_moreInformation.Children.Add(textblock);
            //                            TextBox textbox = new TextBox();
            //                            string[] parts = notes.Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries);
            //                            for (int i11 = 0; i11 < parts.Length; i11++)
            //                            {
            //                                if (i11 != parts.Length - 1)
            //                                {
            //                                    textbox.Text += parts[i11] + Environment.NewLine;
            //                                }
            //                                else
            //                                    textbox.Text += parts[i11];
            //                            }
            //                            panel_moreInformation.Children.Add(textbox);

            //                        }
            //                        #endregion
            //                    }
            //                }

            //            }
            //        }
            //        keyCount++;
            //    }
            //    for (int i = 0; i < x.Length; i++)
            //    {
            //        temp.Add(new DataPoint<DateTime, double>() { X = x[i], Y = y[i] });
            //    }
            //    LineSeries ls = new LineSeries();

            //    SolidColorBrush color1 = new SolidColorBrush();
            //    color1.Color = colurList[colorCount];
            //    ls.LineStroke = color1;
            //    colorCount++;
            //    ls.LineStrokeThickness = 4;

            //    tp.graph_rangeMotion.Series.Add(ls);


            //    tp.graph_rangeMotion.Series[i1].DataSeries = temp;
            //}
            //tp.graph_rangeMotion.Width = double.NaN;
            #endregion



            #region createTable

            selectedKeyList.Clear();

            DataSet ds = new DataSet();
            DataTable dt = new DataTable();
            ds.Tables.Add(dt);

            DataColumn cl1 = new DataColumn("Session", typeof(string));
            cl1.MaxLength = 100;
            dt.Columns.Add(cl1);

            foreach (CheckBox cbx in cbxYAxis.Items)
            {
                if (cbx.IsChecked == true)
                {
                    selectedKeyList.Add(cbx.Content.ToString());
                    DataColumn cl = new DataColumn(cbx.Content.ToString(), typeof(string));
                    cl.MaxLength = 100;
                    dt.Columns.Add(cl);
                }
            }

            foreach (ServiceReference2.session ps in patientSessionList)
            {
                if (ps.ExeID == selectedExe.Uid)
                {
                    List<ServiceReference2.gamePlay> patientGamePlayList = new List<ServiceReference2.gamePlay>();
                    patientGamePlayList = ps.GamePlaylist;

                    List<string> addedKey = new List<string>();

                    DataRow rw = dt.NewRow();
                    dt.Rows.Add(rw);
                    foreach (ServiceReference2.gamePlay gameplay in patientGamePlayList)
                    {
                        foreach (string key in selectedKeyList)
                        {
                            if (gameplay.GameKey.Equals(key) && (gameplay.StageName.Equals(stageName) || stageName == "nostage"))
                            {
                                if (!addedKey.Contains(gameplay.GameKey))
                                {
                                    addedKey.Add(gameplay.GameKey);
                                    //logic to add it in.

                                    rw[gameplay.GameKey] = gameplay.GameValue.ToString();
                                }
                            }
                        }
                        //if (!gameplayIDlist.Contains(gameplay.Uid))
                        //{
                        //    if (gameKey.Equals(gameplay.GameKey) && (gameplay.StageName.Equals(stageName) || stageName == "nostage"))
                        //    {
                        //        xCount++;
                        //        gameplayIDlist.Add(gameplay.Uid);
                        //    }

                        //}
                    }
                    rw["Session"] = ps.Dateofplay.ToString();
                }
            }
            tp.datagrid1.ItemsSource = ds.Tables[0].DefaultView;


            #endregion


            //this.Hide();

            FixedDocument fixedDoc = new FixedDocument();
            PageContent pageContent = new PageContent();
            PageContent pageContent1 = new PageContent();
            FixedPage fixedPage = new FixedPage();
            FixedPage fixedPage1 = new FixedPage();

            StackPanel window = (StackPanel)tp.patientBanner.Parent;
            window.Children.Remove(tp.patientBanner);
            StackPanel sp = new StackPanel();

            StackPanel window1 = (StackPanel)tp.panel_treatmentAnalysis.Parent;
            window1.Children.Remove(tp.panel_treatmentAnalysis);

            StackPanel window2 = (StackPanel)tp.panel_print.Parent;
            window2.Children.Remove(tp.panel_print);
            tp.panel_print.Margin = new Thickness(0, 0, 0, 10);

            sp.Children.Add(tp.panel_print);
            sp.Children.Add(tp.patientBanner);
            sp.Children.Add(tp.panel_treatmentAnalysis);
            sp.RenderTransformOrigin = new Point(0.5, 0.5);
            TransformGroup tg = new TransformGroup();
            RotateTransform rt = new RotateTransform(90);
            tg.Children.Add(rt);
            sp.RenderTransform = tg;
            sp.Margin = new Thickness(15, 50, 15, 15);

            //Create first page of document 
            fixedPage.Children.Add(sp);
            ((System.Windows.Markup.IAddChild)pageContent).AddChild(fixedPage);
            fixedDoc.Pages.Add(pageContent);

            //Create any other required pages here
            StackPanel sp1 = new StackPanel();
            sp1.RenderTransformOrigin = new Point(0.5, 0.5);
            TransformGroup tg1 = new TransformGroup();
            RotateTransform rt1 = new RotateTransform(90);
            tg1.Children.Add(rt1);
            sp1.RenderTransform = tg1;
            sp1.Margin = new Thickness(15, 50, 15, 15);

            StackPanel window5 = (StackPanel)tp.panel_table.Parent;
            window5.Children.Remove(tp.panel_table);
            sp1.Children.Add(tp.panel_table);
            fixedPage1.Children.Add(sp1);
            ((System.Windows.Markup.IAddChild)pageContent1).AddChild(fixedPage1);
            fixedDoc.Pages.Add(pageContent1);

            //View the document   
            documentViewer1.Document = fixedDoc;
            panel_print.Visibility = Visibility.Visible;
            //tp.Show();
            //tp.doWork();
            grid_print.Visibility = Visibility.Visible;
        }


        private void btn_print_close_Click(object sender, System.Windows.RoutedEventArgs e)
        {
            // TODO: Add event handler implementation here.
            grid_print.Visibility = Visibility.Collapsed;
        }


        #endregion

        #region offical kinect sdk methods
        private void initalizeStartKinectSDK()
        {
            nui = new Runtime();

            try
            {
                nui.Initialize(RuntimeOptions.UseDepthAndPlayerIndex | RuntimeOptions.UseSkeletalTracking | RuntimeOptions.UseColor);
            }
            catch (InvalidOperationException)
            {
                System.Windows.MessageBox.Show("Runtime initialization failed. Please make sure Kinect device is plugged in.");
                return;
            }

            try
            {
                nui.VideoStream.Open(ImageStreamType.Video, 2, ImageResolution.Resolution1280x1024, ImageType.Color);
                nui.DepthStream.Open(ImageStreamType.Depth, 2, ImageResolution.Resolution320x240, ImageType.DepthAndPlayerIndex);
            }
            catch (InvalidOperationException)
            {
                System.Windows.MessageBox.Show("Failed to open stream. Please make sure to specify a supported image type and resolution.");
                return;
            }

            lastTime = DateTime.Now;

            nui.DepthFrameReady += new EventHandler<ImageFrameReadyEventArgs>(nui_DepthFrameReady);
            nui.SkeletonFrameReady += new EventHandler<SkeletonFrameReadyEventArgs>(nui_SkeletonFrameReady);
            nui.VideoFrameReady += new EventHandler<ImageFrameReadyEventArgs>(nui_ColorFrameReady);
        }

        // Converts a 16-bit grayscale depth frame which includes player indexes into a 32-bit frame
        // that displays different players in different colors
        byte[] convertDepthFrame(byte[] depthFrame16)
        {
            int player = 0;
            for (int i16 = 0, i32 = 0; i16 < depthFrame16.Length && i32 < depthFrame32.Length; i16 += 2, i32 += 4)
            {
                player = depthFrame16[i16] & 0x07;
                int realDepth = (depthFrame16[i16 + 1] << 5) | (depthFrame16[i16] >> 3);
                // transform 13-bit depth information into an 8-bit intensity appropriate
                // for display (we disregard information in most significant bit)
                byte intensity = (byte)(255 - (255 * realDepth / 0x0fff));

                depthFrame32[i32 + RED_IDX] = 0;
                depthFrame32[i32 + GREEN_IDX] = 0;
                depthFrame32[i32 + BLUE_IDX] = 0;

                // choose different display colors based on player
                switch (player)
                {
                    case 0:
                        depthFrame32[i32 + RED_IDX] = (byte)(intensity / 2);
                        depthFrame32[i32 + GREEN_IDX] = (byte)(intensity / 2);
                        depthFrame32[i32 + BLUE_IDX] = (byte)(intensity / 2);
                        break;
                    case 1:
                        depthFrame32[i32 + RED_IDX] = intensity;
                        break;
                    case 2:
                        depthFrame32[i32 + GREEN_IDX] = intensity;
                        break;
                    case 3:
                        depthFrame32[i32 + RED_IDX] = (byte)(intensity / 4);
                        depthFrame32[i32 + GREEN_IDX] = (byte)(intensity);
                        depthFrame32[i32 + BLUE_IDX] = (byte)(intensity);
                        break;
                    case 4:
                        depthFrame32[i32 + RED_IDX] = (byte)(intensity);
                        depthFrame32[i32 + GREEN_IDX] = (byte)(intensity);
                        depthFrame32[i32 + BLUE_IDX] = (byte)(intensity / 4);
                        break;
                    case 5:
                        depthFrame32[i32 + RED_IDX] = (byte)(intensity);
                        depthFrame32[i32 + GREEN_IDX] = (byte)(intensity / 4);
                        depthFrame32[i32 + BLUE_IDX] = (byte)(intensity);
                        break;
                    case 6:
                        depthFrame32[i32 + RED_IDX] = (byte)(intensity / 2);
                        depthFrame32[i32 + GREEN_IDX] = (byte)(intensity / 2);
                        depthFrame32[i32 + BLUE_IDX] = (byte)(intensity);
                        break;
                    case 7:
                        depthFrame32[i32 + RED_IDX] = (byte)(255 - intensity);
                        depthFrame32[i32 + GREEN_IDX] = (byte)(255 - intensity);
                        depthFrame32[i32 + BLUE_IDX] = (byte)(255 - intensity);
                        break;
                }
            }
            //label3.Content = player.ToString();
            return depthFrame32;
        }

        void nui_DepthFrameReady(object sender, ImageFrameReadyEventArgs e)
        {
            GenerateColoredBytes(e.ImageFrame);

            PlanarImage Image = e.ImageFrame.Image;
            byte[] convertedDepthFrame = convertDepthFrame(Image.Bits);

            //depth.Source = BitmapSource.Create(
            //    Image.Width, Image.Height, 96, 96, PixelFormats.Bgr32, null, convertedDepthFrame, Image.Width * 4);

            ++totalFrames;
            DateTime cur = DateTime.Now;
            if (cur.Subtract(lastTime) > TimeSpan.FromSeconds(1))
            {
                int frameDiff = totalFrames - lastFrames;
                lastFrames = totalFrames;
                lastTime = cur;
                //frameRate.Text = frameDiff.ToString() + " fps";
            }
        }

        private byte[] GenerateColoredBytes(ImageFrame imageFrame)
        {
            int height = imageFrame.Image.Height;
            int width = imageFrame.Image.Width;

            //Depth data for each pixel
            Byte[] depthData = imageFrame.Image.Bits;

            //colorFrame contains color information for all pixels in image
            //Height x Width x 4 (Red, Green, Blue, empty byte)
            Byte[] colorFrame = new byte[imageFrame.Image.Height * imageFrame.Image.Width * 4];

            //Bgr32  - Blue, Green, Red, empty byte
            //Bgra32 - Blue, Green, Red, transparency 
            //You must set transparency for Bgra as .NET defaults a byte to 0 = fully transparent

            //hardcoded locations to Blue, Green, Red (BGR) index positions       
            const int BlueIndex = 0;
            const int GreenIndex = 1;
            const int RedIndex = 2;

            var depthIndex = 0;
            for (var y = 0; y < height; y++)
            {
                var heightOffset = y * width;

                for (var x = 0; x < width; x++)
                {
                    var index = ((width - x - 1) + heightOffset) * 4;
                    //label3.Content = GetPlayerIndex(depthData[depthIndex]).ToString();
                    //var distance = GetDistance(depthData[depthIndex], depthData[depthIndex + 1]);
                    var distance = GetDistanceWithPlayerIndex(depthData[depthIndex], depthData[depthIndex + 1]);

                    if (distance <= 900)
                    {
                        //we are very close
                        colorFrame[index + BlueIndex] = 255;
                        colorFrame[index + GreenIndex] = 0;
                        colorFrame[index + RedIndex] = 0;
                    }
                    else if (distance > 900 && distance < 2000)
                    {
                        //we are a bit further away
                        colorFrame[index + BlueIndex] = 0;
                        colorFrame[index + GreenIndex] = 255;
                        colorFrame[index + RedIndex] = 0;
                    }
                    else if (distance > 2000)
                    {
                        //we are the farthest
                        colorFrame[index + BlueIndex] = 0;
                        colorFrame[index + GreenIndex] = 0;
                        colorFrame[index + RedIndex] = 255;
                    }

                    //Color a player
                    if (GetPlayerIndex(depthData[depthIndex]) > 0)
                    {
                        //we are the farthest
                        colorFrame[index + BlueIndex] = 0;
                        colorFrame[index + GreenIndex] = 255;
                        colorFrame[index + RedIndex] = 255;
                    }

                    //jump two bytes at a time
                    depthIndex += 2;
                }
            }
            return colorFrame;
        }

        private static int GetPlayerIndex(byte firstFrame)
        {
            //returns 0 = no player, 1 = 1st player, 2 = 2nd player...
            return (int)firstFrame & 7;
        }

        private int GetDistanceWithPlayerIndex(byte firstFrame, byte secondFrame)
        {
            //offset by 3 in first byte to get value after player index 
            int distance = (int)(firstFrame >> 3 | secondFrame << 5);
            return distance;
        }

        private Point getDisplayPosition(Joint joint)
        {
            float depthX, depthY;
            nui.SkeletonEngine.SkeletonToDepthImage(joint.Position, out depthX, out depthY);
            depthX = Math.Max(0, Math.Min(depthX * 320, 320));  //convert to 320, 240 space
            depthY = Math.Max(0, Math.Min(depthY * 240, 240));  //convert to 320, 240 space
            int colorX, colorY;
            ImageViewArea iv = new ImageViewArea();
            // only ImageResolution.Resolution640x480 is supported at this point
            nui.NuiCamera.GetColorPixelCoordinatesFromDepthPixel(ImageResolution.Resolution640x480, iv, (int)depthX, (int)depthY, (short)0, out colorX, out colorY);

            // map back to skeleton.Width & skeleton.Height
            return new Point((int)(skeleton.Width * colorX / 640.0), (int)(skeleton.Height * colorY / 480));
        }

        Polyline getBodySegment(Microsoft.Research.Kinect.Nui.JointsCollection joints, Brush brush, params JointID[] ids)
        {
            PointCollection points = new PointCollection(ids.Length);
            for (int i = 0; i < ids.Length; ++i)
            {
                points.Add(getDisplayPosition(joints[ids[i]]));
            }
            Polyline polyline = new Polyline();
            polyline.Points = points;
            polyline.Stroke = brush;
            polyline.StrokeThickness = 10;
            return polyline;
        }

        void nui_SkeletonFrameReady(object sender, SkeletonFrameReadyEventArgs e)
        {
            if (selectedtreatment == "Fugl Meyer")
            {
                #region Fugl Meyer
                SkeletonFrame skeletonFrame = e.SkeletonFrame;
                int iSkeleton = 0;
                #region brushes
                Brush[] brushes = new Brush[6];
                brushes[0] = new SolidColorBrush(Color.FromRgb(255, 0, 0));
                brushes[1] = new SolidColorBrush(Color.FromRgb(0, 255, 0));
                brushes[2] = new SolidColorBrush(Color.FromRgb(64, 255, 255));
                brushes[3] = new SolidColorBrush(Color.FromRgb(255, 255, 64));
                brushes[4] = new SolidColorBrush(Color.FromRgb(255, 64, 255));
                brushes[5] = new SolidColorBrush(Color.FromRgb(128, 128, 255));
                #endregion
                skeleton.Children.Clear();
                Brush brush = null;
                foreach (SkeletonData data in skeletonFrame.Skeletons)
                {
                    if (SkeletonTrackingState.Tracked == data.TrackingState)
                    {
                        // Draw bones
                        brush = brushes[iSkeleton % brushes.Length];
                        skeleton.Children.Add(getBodySegment(data.Joints, brush, JointID.HipCenter, JointID.Spine, JointID.ShoulderCenter, JointID.Head));
                        skeleton.Children.Add(getBodySegment(data.Joints, brush, JointID.ShoulderCenter, JointID.ShoulderLeft, JointID.ElbowLeft, JointID.WristLeft, JointID.HandLeft));
                        skeleton.Children.Add(getBodySegment(data.Joints, brush, JointID.ShoulderCenter, JointID.ShoulderRight, JointID.ElbowRight, JointID.WristRight, JointID.HandRight));
                        skeleton.Children.Add(getBodySegment(data.Joints, brush, JointID.HipCenter, JointID.HipLeft, JointID.KneeLeft, JointID.AnkleLeft, JointID.FootLeft));
                        skeleton.Children.Add(getBodySegment(data.Joints, brush, JointID.HipCenter, JointID.HipRight, JointID.KneeRight, JointID.AnkleRight, JointID.FootRight));

                        //// Draw joints
                        //foreach (Joint joint in data.Joints)
                        //{
                        //    Point jointPos = getDisplayPosition(joint);
                        //    Line jointLine = new Line();
                        //    jointLine.X1 = jointPos.X - 3;
                        //    jointLine.X2 = jointLine.X1 + 6;
                        //    jointLine.Y1 = jointLine.Y2 = jointPos.Y;
                        //    jointLine.Stroke = jointColors[joint.ID];
                        //    jointLine.StrokeThickness = 6;
                        //    skeleton.Children.Add(jointLine);
                        //}

                        // Draw joints
                        foreach (Joint joint in data.Joints)
                        {
                            if (joint.ID != data.Joints[JointID.AnkleLeft].ID
                                && joint.ID != data.Joints[JointID.Spine].ID
                                && joint.ID != data.Joints[JointID.WristRight].ID
                                && joint.ID != data.Joints[JointID.WristLeft].ID
                                && joint.ID != data.Joints[JointID.AnkleRight].ID
                                && joint.ID != data.Joints[JointID.FootLeft].ID
                                && joint.ID != data.Joints[JointID.FootRight].ID
                                && joint.ID != data.Joints[JointID.ShoulderCenter].ID
                                && joint.ID != data.Joints[JointID.HandLeft].ID
                                && joint.ID != data.Joints[JointID.HandRight].ID
                                )
                            {
                                Point jointPos = getDisplayPosition(joint);
                                Line jointLine = new Line();
                                jointLine.X1 = jointPos.X - 3;
                                jointLine.X2 = jointLine.X1 + 6;
                                jointLine.Y1 = jointLine.Y2 = jointPos.Y;
                                jointLine.Stroke = jointColors[joint.ID];
                                jointLine.StrokeThickness = 6;
                                skeleton.Children.Add(jointLine);
                            }
                        }
                    }
                    iSkeleton++;

                    if (startShowed == false)
                    {
                        startShowed = true;
                        sp_k_controlPanel_start.Visibility = Visibility.Visible;
                    }

                    #region get joint data
                    float HandLeftX = data.Joints[JointID.HandLeft].Position.X;
                    if (HandLeftX != 0)
                    {
                        #region vector3d
                        float HandLeftY = data.Joints[JointID.HandLeft].Position.Y;
                        float HandLeftZ = data.Joints[JointID.HandLeft].Position.Z;
                        Vector3D handLeftVector = new Vector3D(HandLeftX, HandLeftY, HandLeftZ);
                        handLeftVector.Normalize();

                        float ElbowLeftX = data.Joints[JointID.ElbowLeft].Position.X;
                        float ElbowLeftY = data.Joints[JointID.ElbowLeft].Position.Y;
                        float ElbowLeftZ = data.Joints[JointID.ElbowLeft].Position.Z;
                        Vector3D ElbowLeftEVector = new Vector3D(ElbowLeftX, ElbowLeftY, ElbowLeftZ);
                        ElbowLeftEVector.Normalize();

                        float ShoulderLeftX = data.Joints[JointID.ShoulderLeft].Position.X;
                        float ShoulderLeftY = data.Joints[JointID.ShoulderLeft].Position.Y;
                        float ShoulderLeftZ = data.Joints[JointID.ShoulderLeft].Position.Z;
                        Vector3D ShoulderLeftVector = new Vector3D(ShoulderLeftX, ShoulderLeftY, ShoulderLeftZ);
                        ShoulderLeftVector.Normalize();

                        float headX = data.Joints[JointID.Head].Position.X;
                        float headY = data.Joints[JointID.Head].Position.Y;
                        float headZ = data.Joints[JointID.Head].Position.Z;
                        Vector3D HeadVector = new Vector3D(headX, headY, headZ);
                        HeadVector.Normalize();
                        Color userColor = Colors.Black;
                        if (2500 < headZ)
                        {
                            if (headZ < 3000)
                            {
                                userColor = (Color)ColorConverter.ConvertFromString("#FFFFD700");
                            }
                        }

                        float ShoulderCenterX = data.Joints[JointID.ShoulderCenter].Position.X;
                        float ShoulderCenterY = data.Joints[JointID.ShoulderCenter].Position.Y;
                        float ShoulderCenterZ = data.Joints[JointID.ShoulderCenter].Position.Z;
                        Vector3D ShoulderCenterVector = new Vector3D(ShoulderCenterX, ShoulderCenterY, ShoulderCenterZ);
                        ShoulderCenterVector.Normalize();

                        float ShoulderRightX = data.Joints[JointID.ShoulderRight].Position.X;
                        float ShoulderRightY = data.Joints[JointID.ShoulderRight].Position.Y;
                        float ShoulderRightZ = data.Joints[JointID.ShoulderRight].Position.Z;
                        Vector3D ShoulderRightVector = new Vector3D(ShoulderRightX, ShoulderRightY, ShoulderRightZ);
                        ShoulderRightVector.Normalize();
                        #region invis arm
                        float fakeRightShoulderX = data.Joints[JointID.ShoulderRight].Position.X;
                        float fakeRightShoulderY = data.Joints[JointID.ShoulderRight].Position.Y;
                        float fakeRightShoulderZ = data.Joints[JointID.ShoulderRight].Position.Z - 0.5f;
                        Vector3D fakeRightShoulder3D = new Vector3D(fakeRightShoulderX, fakeRightShoulderY, fakeRightShoulderZ - 0.5f);
                        fakeRightShoulder3D.Normalize();

                        float fakeRightShoulderXAxis3 = data.Joints[JointID.ShoulderRight].Position.X + 0.5f;
                        float fakeRightShoulderYAxis3 = data.Joints[JointID.ShoulderRight].Position.Y;
                        float fakeRightShoulderZAxis3 = data.Joints[JointID.ShoulderRight].Position.Z;
                        Vector3D fakeRightShoulder3DAxis3 = new Vector3D(fakeRightShoulderXAxis3 + 0.5f, fakeRightShoulderYAxis3, fakeRightShoulderZAxis3);
                        fakeRightShoulder3DAxis3.Normalize();

                        float fakeLeftShoulderX = data.Joints[JointID.ShoulderLeft].Position.X;
                        float fakeLeftShoulderY = data.Joints[JointID.ShoulderLeft].Position.Y;
                        float fakeLeftShoulderZ = data.Joints[JointID.ShoulderLeft].Position.Z - 0.5f;
                        Vector3D fakeLeftShoulder3D = new Vector3D(fakeLeftShoulderX, fakeLeftShoulderY, fakeLeftShoulderZ - 0.5f);
                        fakeLeftShoulder3D.Normalize();

                        float fakeLeftShoulderXAxis3 = data.Joints[JointID.ShoulderLeft].Position.X - 0.5f;
                        float fakeLeftShoulderYAxis3 = data.Joints[JointID.ShoulderLeft].Position.Y;
                        float fakeLeftShoulderZAxis3 = data.Joints[JointID.ShoulderLeft].Position.Z;
                        Vector3D fakeLeftShoulder3DAxis3 = new Vector3D(fakeLeftShoulderXAxis3 - 0.5f, fakeLeftShoulderYAxis3, fakeLeftShoulderZAxis3);
                        fakeLeftShoulder3DAxis3.Normalize();

                        #endregion

                        float HandRightX = data.Joints[JointID.HandRight].Position.X;
                        float HandRightY = data.Joints[JointID.HandRight].Position.Y;
                        float HandRightZ = data.Joints[JointID.HandRight].Position.Z;
                        Vector3D HandRightVector = new Vector3D(HandRightX, HandRightY, HandRightZ);
                        HandRightVector.Normalize();

                        float ElbowRightX = data.Joints[JointID.ElbowRight].Position.X;
                        float ElbowRightY = data.Joints[JointID.ElbowRight].Position.Y;
                        float ElbowRightZ = data.Joints[JointID.ElbowRight].Position.Z;
                        Vector3D ElbowRightVector = new Vector3D(ElbowRightX, ElbowRightY, ElbowRightZ);
                        ElbowRightVector.Normalize();

                        float HipCenterX = data.Joints[JointID.HipCenter].Position.X;
                        float HipCenterY = data.Joints[JointID.HipCenter].Position.Y;
                        float HipCenterZ = data.Joints[JointID.HipCenter].Position.Z;
                        Vector3D HipCenterVector = new Vector3D(HipCenterX, HipCenterY, HipCenterZ);
                        HipCenterVector.Normalize();

                        float HipLeftX = data.Joints[JointID.HipLeft].Position.X;
                        float HipLeftY = data.Joints[JointID.HipLeft].Position.Y;
                        float HipLeftZ = data.Joints[JointID.HipLeft].Position.Z;
                        Vector3D HipLeftVector = new Vector3D(HipLeftX, HipLeftY, HipLeftZ);
                        HipLeftVector.Normalize();

                        float KneeLeftX = data.Joints[JointID.KneeLeft].Position.X;
                        float KneeLeftY = data.Joints[JointID.KneeLeft].Position.Y;
                        float KneeLeftZ = data.Joints[JointID.KneeLeft].Position.Z;
                        Vector3D KneeLeftVector = new Vector3D(KneeLeftX, KneeLeftY, KneeLeftZ);
                        KneeLeftVector.Normalize();

                        float FootLeftX = data.Joints[JointID.FootLeft].Position.X;
                        float FootLeftY = data.Joints[JointID.FootLeft].Position.Y;
                        float FootLeftZ = data.Joints[JointID.FootLeft].Position.Z;
                        Vector3D FootLeftVector = new Vector3D(FootLeftX, FootLeftY, FootLeftZ);
                        FootLeftVector.Normalize();

                        float HipRightX = data.Joints[JointID.HipRight].Position.X;
                        float HipRightY = data.Joints[JointID.HipRight].Position.Y;
                        float HipRightZ = data.Joints[JointID.HipRight].Position.Z;
                        Vector3D HipRightVector = new Vector3D(HipRightX, HipRightY, HipRightZ);
                        HipRightVector.Normalize();
                        #region invis hip
                        float fakeRightHipX = data.Joints[JointID.HipRight].Position.X;
                        float fakeRightHipY = data.Joints[JointID.HipRight].Position.Y;
                        float fakeRightHipZ = data.Joints[JointID.HipRight].Position.Z - 0.5f;
                        Vector3D fakeRightHipX3D = new Vector3D(fakeRightHipX, fakeRightHipY, fakeRightHipZ - 0.5f);
                        fakeRightHipX3D.Normalize();

                        float fakeRightHipXAxis3 = data.Joints[JointID.HipRight].Position.X + 0.5f;
                        float fakeRightHipYAxis3 = data.Joints[JointID.HipRight].Position.Y;
                        float fakeRightHipZAxis3 = data.Joints[JointID.HipRight].Position.Z;
                        Vector3D fakeRightHipX3DAxis3 = new Vector3D(fakeRightHipX + 0.5f, fakeRightHipY, fakeRightHipZ);
                        fakeRightHipX3DAxis3.Normalize();

                        float fakeLeftHipX = data.Joints[JointID.HipLeft].Position.X;
                        float fakeLeftHipY = data.Joints[JointID.HipLeft].Position.Y;
                        float fakeLeftHipZ = data.Joints[JointID.HipLeft].Position.Z - 0.5f;
                        Vector3D fakeLeftHipX3D = new Vector3D(fakeLeftHipX, fakeLeftHipY, fakeLeftHipZ - 0.5f);
                        fakeLeftHipX3D.Normalize();

                        float fakeLeftHipXAxis3 = data.Joints[JointID.HipLeft].Position.X + 0.5f;
                        float fakeLeftHipYAxis3 = data.Joints[JointID.HipLeft].Position.Y;
                        float fakeLeftHipZAxis3 = data.Joints[JointID.HipLeft].Position.Z;
                        Vector3D fakeLeftHipX3DAxis3 = new Vector3D(fakeLeftHipX + 0.5f, fakeLeftHipY, fakeLeftHipZ);
                        fakeLeftHipX3DAxis3.Normalize();
                        #endregion

                        float KneeRightX = data.Joints[JointID.KneeRight].Position.X;
                        float KneeRightY = data.Joints[JointID.KneeRight].Position.Y;
                        float KneeRightZ = data.Joints[JointID.KneeRight].Position.Z;
                        Vector3D KneeRightVector = new Vector3D(KneeRightX, KneeRightY, KneeRightZ);
                        KneeRightVector.Normalize();

                        float FootRightX = data.Joints[JointID.FootRight].Position.X;
                        float FootRightY = data.Joints[JointID.FootRight].Position.Y;
                        float FootRightZ = data.Joints[JointID.FootRight].Position.Z;
                        Vector3D FootRightVector = new Vector3D(FootRightX, FootRightY, FootRightZ);
                        FootRightVector.Normalize();
                        #endregion
                        //#region Draw skeleton points
                        //if (headX != 0 && headY != 0)
                        //{
                        //    #region DrawLine for joints
                        //    Line myNeck = new Line();
                        //    myNeck.Stroke = Brushes.Black;
                        //    myNeck.X1 = Convert.ToDouble(headX + 15);
                        //    myNeck.Y1 = Convert.ToDouble(headY + 15);
                        //    myNeck.X2 = Convert.ToDouble(ShoulderCenterX + 15);
                        //    myNeck.Y2 = Convert.ToDouble(ShoulderCenterY + 15);
                        //    myNeck.StrokeThickness = 5;
                        //    skeleton.Children.Add(myNeck);

                        //    Line myRightUpperLimbLower = new Line();
                        //    myRightUpperLimbLower.Stroke = Brushes.Black;
                        //    myRightUpperLimbLower.X1 = Convert.ToDouble(ElbowRightX + 15);
                        //    myRightUpperLimbLower.Y1 = Convert.ToDouble(ElbowRightY + 15);
                        //    myRightUpperLimbLower.X2 = Convert.ToDouble(HandRightX + 15);
                        //    myRightUpperLimbLower.Y2 = Convert.ToDouble(HandRightY + 15);
                        //    myRightUpperLimbLower.StrokeThickness = 5;
                        //    skeleton.Children.Add(myRightUpperLimbLower);

                        //    Line myRightUpperLimbUpper = new Line();
                        //    myRightUpperLimbUpper.Stroke = Brushes.Black;
                        //    myRightUpperLimbUpper.X1 = Convert.ToDouble(ElbowRightX + 15);
                        //    myRightUpperLimbUpper.Y1 = Convert.ToDouble(ElbowRightY + 15);
                        //    myRightUpperLimbUpper.X2 = Convert.ToDouble(ShoulderRightX + 15);
                        //    myRightUpperLimbUpper.Y2 = Convert.ToDouble(ShoulderRightY + 15);
                        //    myRightUpperLimbUpper.StrokeThickness = 5;
                        //    skeleton.Children.Add(myRightUpperLimbUpper);

                        //    Line myRightShoulder = new Line();
                        //    myRightShoulder.Stroke = Brushes.Black;
                        //    myRightShoulder.X1 = Convert.ToDouble(ShoulderCenterX + 15);
                        //    myRightShoulder.Y1 = Convert.ToDouble(ShoulderCenterY + 15);
                        //    myRightShoulder.X2 = Convert.ToDouble(ShoulderRightX + 15);
                        //    myRightShoulder.Y2 = Convert.ToDouble(ShoulderRightY + 15);
                        //    myRightShoulder.StrokeThickness = 5;
                        //    skeleton.Children.Add(myRightShoulder);

                        //    Line myLeftUpperLimbLower = new Line();
                        //    myLeftUpperLimbLower.Stroke = Brushes.Black;
                        //    myLeftUpperLimbLower.X1 = Convert.ToDouble(ElbowLeftX + 15);
                        //    myLeftUpperLimbLower.Y1 = Convert.ToDouble(ElbowLeftY + 15);
                        //    myLeftUpperLimbLower.X2 = Convert.ToDouble(HandLeftX + 15);
                        //    myLeftUpperLimbLower.Y2 = Convert.ToDouble(HandLeftY + 15);
                        //    myLeftUpperLimbLower.StrokeThickness = 5;
                        //    skeleton.Children.Add(myLeftUpperLimbLower);

                        //    Line myLeftUpperLimbUpper = new Line();
                        //    myLeftUpperLimbUpper.Stroke = Brushes.Black;
                        //    myLeftUpperLimbUpper.X1 = Convert.ToDouble(ElbowLeftX + 15);
                        //    myLeftUpperLimbUpper.Y1 = Convert.ToDouble(ElbowLeftY + 15);
                        //    myLeftUpperLimbUpper.X2 = Convert.ToDouble(ShoulderLeftX + 15);
                        //    myLeftUpperLimbUpper.Y2 = Convert.ToDouble(ShoulderLeftY + 15);
                        //    myLeftUpperLimbUpper.StrokeThickness = 5;
                        //    skeleton.Children.Add(myLeftUpperLimbUpper);

                        //    Line myLeftShoulder = new Line();
                        //    myLeftShoulder.Stroke = Brushes.Black;
                        //    myLeftShoulder.X1 = Convert.ToDouble(ShoulderCenterX + 15);
                        //    myLeftShoulder.Y1 = Convert.ToDouble(ShoulderCenterY + 15);
                        //    myLeftShoulder.X2 = Convert.ToDouble(ShoulderLeftX + 15);
                        //    myLeftShoulder.Y2 = Convert.ToDouble(ShoulderLeftY + 15);
                        //    skeleton.Children.Add(myLeftShoulder);

                        //    //Legs
                        //    Line myLeftLowerLimbLower = new Line();
                        //    myLeftLowerLimbLower.Stroke = Brushes.Black;
                        //    myLeftLowerLimbLower.X1 = Convert.ToDouble(FootLeftX + 15);
                        //    myLeftLowerLimbLower.Y1 = Convert.ToDouble(FootLeftY + 15);
                        //    myLeftLowerLimbLower.X2 = Convert.ToDouble(KneeLeftX + 15);
                        //    myLeftLowerLimbLower.Y2 = Convert.ToDouble(KneeLeftY + 15);
                        //    myLeftLowerLimbLower.StrokeThickness = 5;
                        //    skeleton.Children.Add(myLeftLowerLimbLower);

                        //    Line myLeftLowerLimbUpper = new Line();
                        //    myLeftLowerLimbUpper.Stroke = Brushes.Black;
                        //    myLeftLowerLimbUpper.X1 = Convert.ToDouble(KneeLeftX + 15);
                        //    myLeftLowerLimbUpper.Y1 = Convert.ToDouble(KneeLeftY + 15);
                        //    myLeftLowerLimbUpper.X2 = Convert.ToDouble(HipLeftX + 15);
                        //    myLeftLowerLimbUpper.Y2 = Convert.ToDouble(HipLeftY + 15);
                        //    myLeftLowerLimbUpper.StrokeThickness = 5;
                        //    skeleton.Children.Add(myLeftLowerLimbUpper);

                        //    Line myRightLowerLimbLower = new Line();
                        //    myRightLowerLimbLower.Stroke = Brushes.Black;
                        //    myRightLowerLimbLower.X1 = Convert.ToDouble(FootRightX + 15);
                        //    myRightLowerLimbLower.Y1 = Convert.ToDouble(FootRightY + 15);
                        //    myRightLowerLimbLower.X2 = Convert.ToDouble(KneeRightX + 15);
                        //    myRightLowerLimbLower.Y2 = Convert.ToDouble(KneeRightY + 15);
                        //    myRightLowerLimbLower.StrokeThickness = 5;
                        //    skeleton.Children.Add(myRightLowerLimbLower);

                        //    Line myRightLowerLimbUpper = new Line();
                        //    myRightLowerLimbUpper.Stroke = Brushes.Black;
                        //    myRightLowerLimbUpper.X1 = Convert.ToDouble(KneeRightX + 15);
                        //    myRightLowerLimbUpper.Y1 = Convert.ToDouble(KneeRightY + 15);
                        //    myRightLowerLimbUpper.X2 = Convert.ToDouble(HipRightX + 15);
                        //    myRightLowerLimbUpper.Y2 = Convert.ToDouble(HipRightX + 15);
                        //    myRightLowerLimbUpper.StrokeThickness = 5;
                        //    skeleton.Children.Add(myRightLowerLimbUpper);

                        //    Line myLeftLowerWrist = new Line();
                        //    myLeftLowerWrist.Stroke = Brushes.Black;
                        //    myLeftLowerWrist.X1 = Convert.ToDouble(HipCenterX + 15);
                        //    myLeftLowerWrist.Y1 = Convert.ToDouble(HipCenterY + 15);
                        //    myLeftLowerWrist.X2 = Convert.ToDouble(HipLeftX + 15);
                        //    myLeftLowerWrist.Y2 = Convert.ToDouble(HipLeftY + 15);
                        //    myLeftLowerWrist.StrokeThickness = 5;
                        //    skeleton.Children.Add(myLeftLowerWrist);

                        //    Line myRightLowerWrist = new Line();
                        //    myRightLowerWrist.Stroke = Brushes.Black;
                        //    myRightLowerWrist.Y1 = Convert.ToDouble(HipCenterY + 15);
                        //    myRightLowerWrist.X2 = Convert.ToDouble(HipRightX + 15);
                        //    myRightLowerWrist.Y2 = Convert.ToDouble(HipRightY + 15);
                        //    myRightLowerWrist.StrokeThickness = 5;
                        //    skeleton.Children.Add(myRightLowerWrist);

                        //    Line myLeftUpperWrist = new Line();
                        //    myLeftUpperWrist.Stroke = Brushes.Black;
                        //    myLeftUpperWrist.X1 = Convert.ToDouble(HipCenterX + 15);
                        //    myLeftUpperWrist.Y1 = Convert.ToDouble(HipCenterY + 15);
                        //    myLeftUpperWrist.X2 = Convert.ToDouble(ShoulderLeftX + 15);
                        //    myLeftUpperWrist.Y2 = Convert.ToDouble(ShoulderLeftY + 15);
                        //    myLeftUpperWrist.StrokeThickness = 5;
                        //    skeleton.Children.Add(myLeftUpperWrist);

                        //    Line myRightUpperWrist = new Line();
                        //    myRightUpperWrist.Stroke = Brushes.Black;
                        //    myRightUpperWrist.X1 = Convert.ToDouble(HipCenterX + 15);
                        //    myRightUpperWrist.Y1 = Convert.ToDouble(HipCenterY + 15);
                        //    myRightUpperWrist.X2 = Convert.ToDouble(ShoulderRightX + 15);
                        //    myRightUpperWrist.Y2 = Convert.ToDouble(ShoulderRightY + 15);
                        //    myRightUpperWrist.StrokeThickness = 5;
                        //    skeleton.Children.Add(myRightUpperWrist);
                        //    #endregion

                        //    #region DrawCircle for each point
                        //    DrawCircle(headX, headY, userColor);
                        //    //DrawCircle(neckX, neckY, userColor);
                        //    //DrawCircle(leftShoulderX, leftShoulderY, userColor);
                        //    //DrawCircle(leftElbowX, leftElbowY, userColor);
                        //    //DrawCircle(leftHandX, leftHandY, userColor);
                        //    //DrawCircle(waistX, waistY, userColor);
                        //    //DrawCircle(rightShoulderX, rightShoulderY, userColor);
                        //    //DrawCircle(rightElbowX, rightElbowY, userColor);
                        //    //DrawCircle(rightHandX, rightHandY, userColor);
                        //    //DrawCircle(leftHipX, leftHipY, userColor);
                        //    //DrawCircle(leftKneeX, leftKneeY, userColor);
                        //    //DrawCircle(leftFootX, leftFootY, userColor);
                        //    //DrawCircle(rightHipX, rightHipY, userColor);
                        //    //DrawCircle(rightKneeX, rightKneeY, userColor);
                        //    //DrawCircle(rightFootX, rightFootY, userColor);
                        //    gotUser = true;
                        //    #endregion
                        //}
                        //#endregion


                        lbl_k_jointName.Text = tbx_joint.Text;
                        tbx_joint_Copy.Text = "2";
                        if (tbx_joint_Copy.Text != "")
                        {

                            #region calculate angle

                            int joint = Convert.ToInt16(tbx_joint_Copy.Text);
                            if (joint == 2)//Left Shoulders 2
                            {
                                Vector3D leftShoulderV1 = ElbowLeftEVector - ShoulderLeftVector;
                                Vector3D leftShoulderV2 = HipLeftVector - ShoulderLeftVector;
                                double leftShoulderAngle = Vector3D.AngleBetween(leftShoulderV1, leftShoulderV2);
                                now = Math.Round(leftShoulderAngle, 3);

                                if (maxActive == 0 && minActive == 0)
                                {
                                    if (checkbx_active.IsChecked == true)
                                    {
                                        maxActive = now;
                                        minActive = now;
                                        lowSystemTime = DateTime.Now;
                                    }
                                }
                                if (maxPassive == 0 && minPassive == 0)
                                {
                                    if (checkbx_passive.IsChecked == true)
                                    {
                                        maxPassive = now;
                                        minPassive = now;
                                        lowSystemTime = DateTime.Now;
                                    }
                                }
                                if (checkbx_passive.IsChecked == true)
                                {

                                    max = maxPassive;
                                    min = minPassive;
                                }
                                else if (checkbx_active.IsChecked == true)
                                {
                                    max = maxActive;
                                    min = minActive;
                                }


                                if (now > max)
                                {
                                    max = now;
                                }
                                else if (now < min)
                                {
                                    min = now;
                                }


                                if (HipCenterZ < HandLeftZ)
                                {
                                    if ((HipCenterX - 50.0) < HandLeftX)
                                    {
                                        if (HandLeftZ < (HipCenterX + 50.0))
                                        {
                                            if ((HipCenterY - 100.0) < HandLeftY)
                                            {
                                                if (HandLeftY < (HipCenterY + 100.0))
                                                {
                                                    dif = (DateTime.Now - lowSystemTime).Seconds;
                                                }
                                            }
                                        }
                                    }
                                }
                                else
                                { }
                            }
                            if (joint == 3)//Right Shoulders 3
                            {
                                Vector3D rightShoulderV1 = ElbowRightVector - ShoulderRightVector;
                                Vector3D rightShoulderV2 = HipRightVector - ShoulderRightVector;
                                double rightShoulderAngle = Vector3D.AngleBetween(rightShoulderV1, rightShoulderV2);
                                now = Math.Round(rightShoulderAngle, 3);

                                if (maxActive == 0 && minActive == 0)
                                {
                                    if (checkbx_active.IsChecked == true)
                                    {
                                        maxActive = now;
                                        minActive = now;
                                        lowSystemTime = DateTime.Now;
                                    }
                                }
                                if (maxPassive == 0 && minPassive == 0)
                                {
                                    if (checkbx_passive.IsChecked == true)
                                    {
                                        maxPassive = now;
                                        minPassive = now;
                                        lowSystemTime = DateTime.Now;
                                    }
                                }
                                if (checkbx_passive.IsChecked == true)
                                {

                                    max = maxPassive;
                                    min = minPassive;
                                }
                                else if (checkbx_active.IsChecked == true)
                                {
                                    max = maxActive;
                                    min = minActive;
                                }


                                if (now > max)
                                {
                                    max = now;
                                }
                                if (now < min)
                                {
                                    min = now;
                                }

                                if (HipCenterZ < HandRightZ)
                                {
                                    if ((HipCenterX - 50.0) < HandRightX)
                                    {
                                        if (HandRightX < (HipCenterX + 50.0))
                                        {
                                            if ((HipCenterY - 100.0) < HandRightY)
                                            {
                                                if (HandRightY < (HipCenterY + 100.0))
                                                {
                                                    dif = (DateTime.Now - lowSystemTime).Seconds;
                                                }
                                            }
                                        }
                                    }
                                }
                                else
                                { }
                            }
                            else if (joint == 4)//leftElbow
                            {
                                Vector3D leftElbowV1 = ShoulderLeftVector - ElbowLeftEVector;
                                Vector3D leftElbowV2 = handLeftVector - ElbowLeftEVector;
                                double leftElbowAngle = Vector3D.AngleBetween(leftElbowV1, leftElbowV2);
                                now = Math.Round(leftElbowAngle, 3);

                                if (maxActive == 0 && minActive == 0)
                                {
                                    if (checkbx_active.IsChecked == true)
                                    {
                                        maxActive = now;
                                        minActive = now;
                                        lowSystemTime = DateTime.Now;
                                    }
                                }
                                if (maxPassive == 0 && minPassive == 0)
                                {
                                    if (checkbx_passive.IsChecked == true)
                                    {
                                        maxPassive = now;
                                        minPassive = now;
                                        lowSystemTime = DateTime.Now;
                                    }
                                }
                                if (checkbx_passive.IsChecked == true)
                                {
                                    max = maxPassive;
                                    min = minPassive;
                                }
                                else if (checkbx_active.IsChecked == true)
                                {
                                    max = maxActive;
                                    min = minActive;
                                }

                                if (now > max)
                                {
                                    max = now;
                                }
                                if (now < min)
                                {
                                    min = now;
                                }

                                if ((headZ - 100.0) > HandLeftZ)
                                {
                                    if (HandLeftZ < (headZ + 50))
                                    {
                                        if ((headX - 25.0) < HandLeftX)
                                        {
                                            if (HandLeftX < (headX + 25.0))
                                            {
                                                if ((headY - 20.0) < HandLeftY)
                                                {
                                                    if (HandLeftY < (headY + 20.0))
                                                    {

                                                        dif = (DateTime.Now - lowSystemTime).Seconds;
                                                    }
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                            else if (joint == 5)//rightElbow
                            {
                                Vector3D rightElbowV1 = ShoulderRightVector - ElbowRightVector;
                                Vector3D rightElbowV2 = HandRightVector - ElbowRightVector;
                                double rightElbowAngle = Vector3D.AngleBetween(rightElbowV1, rightElbowV2);
                                now = Math.Round(rightElbowAngle, 3);

                                if (maxActive == 0 && minActive == 0)
                                {
                                    if (checkbx_active.IsChecked == true)
                                    {
                                        maxActive = now;
                                        minActive = now;
                                        lowSystemTime = DateTime.Now;
                                    }
                                }
                                if (maxPassive == 0 && minPassive == 0)
                                {
                                    if (checkbx_passive.IsChecked == true)
                                    {
                                        maxPassive = now;
                                        minPassive = now;
                                        lowSystemTime = DateTime.Now;
                                    }
                                }
                                if (checkbx_passive.IsChecked == true)
                                {

                                    max = maxPassive;
                                    min = minPassive;
                                }
                                else if (checkbx_active.IsChecked == true)
                                {
                                    max = maxActive;
                                    min = minActive;
                                }


                                if (now > max)
                                {
                                    max = now;
                                }
                                if (now < min)
                                {
                                    min = now;
                                }

                                if ((headZ - 100.0) > HandRightZ)
                                {
                                    if (HandRightZ < (headZ + 50))
                                    {
                                        if ((headX - 20.0) < HandRightX)
                                        {
                                            if (HandRightX < (headX + 20.0))
                                            {
                                                if ((headY - 20.0) < HandRightY)
                                                {
                                                    if (HandRightY < (headY + 20.0))
                                                    {
                                                        dif = (DateTime.Now - lowSystemTime).Seconds;
                                                    }
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                            else if (joint == 8)//Torso
                            {
                                Vector3D spine = HipCenterVector - ShoulderCenterVector;
                                Vector3D leftShoulder = ShoulderLeftVector - ShoulderCenterVector;
                                double Torso = Vector3D.AngleBetween(spine, leftShoulder);
                                now = Math.Round(Torso, 3);

                                if (maxActive == 0 && minActive == 0)
                                {
                                    if (checkbx_active.IsChecked == true)
                                    {
                                        maxActive = now;
                                        minActive = now;
                                        lowSystemTime = DateTime.Now;
                                    }
                                }
                                if (maxPassive == 0 && minPassive == 0)
                                {
                                    if (checkbx_passive.IsChecked == true)
                                    {
                                        maxPassive = now;
                                        minPassive = now;
                                        lowSystemTime = DateTime.Now;
                                    }
                                }
                                if (checkbx_passive.IsChecked == true)
                                {

                                    max = maxPassive;
                                    min = minPassive;
                                }
                                else if (checkbx_active.IsChecked == true)
                                {
                                    max = maxActive;
                                    min = minActive;
                                }


                                if (now > max)
                                {
                                    max = now;
                                }
                                if (now < min)
                                {
                                    min = now;
                                }

                            }
                            else if (joint == 9)//Left hips 9 
                            {
                                Vector3D leftHipV1 = KneeRightVector - HipLeftVector;
                                Vector3D leftHipV2 = KneeLeftVector - HipLeftVector;
                                double leftHipAngle = Vector3D.AngleBetween(leftHipV1, leftHipV2);
                                now = Math.Round(leftHipAngle, 3);

                                if (maxActive == 0 && minActive == 0)
                                {
                                    if (checkbx_active.IsChecked == true)
                                    {
                                        maxActive = now;
                                        minActive = now;
                                        lowSystemTime = DateTime.Now;
                                    }
                                }
                                if (maxPassive == 0 && minPassive == 0)
                                {
                                    if (checkbx_passive.IsChecked == true)
                                    {
                                        maxPassive = now;
                                        minPassive = now;
                                        lowSystemTime = DateTime.Now;
                                    }
                                }
                                if (checkbx_passive.IsChecked == true)
                                {

                                    max = maxPassive;
                                    min = minPassive;
                                }
                                else if (checkbx_active.IsChecked == true)
                                {
                                    max = maxActive;
                                    min = minActive;
                                }


                                if (now > max)
                                {
                                    max = now;
                                    dif = (DateTime.Now - lowSystemTime).Seconds;
                                }
                                if (now < min)
                                {
                                    min = now;
                                }

                            }
                            else if (joint == 10)//Right hips 10 
                            {
                                Vector3D rightHipV1 = KneeLeftVector - HipRightVector;
                                Vector3D rightHipV2 = KneeRightVector - HipRightVector;
                                double rightHipAngle = Vector3D.AngleBetween(rightHipV1, rightHipV2);
                                now = Math.Round(rightHipAngle, 3);

                                if (maxActive == 0 && minActive == 0)
                                {
                                    if (checkbx_active.IsChecked == true)
                                    {
                                        maxActive = now;
                                        minActive = now;
                                        lowSystemTime = DateTime.Now;
                                    }
                                }
                                if (maxPassive == 0 && minPassive == 0)
                                {
                                    if (checkbx_passive.IsChecked == true)
                                    {
                                        maxPassive = now;
                                        minPassive = now;
                                        lowSystemTime = DateTime.Now;
                                    }
                                }
                                if (checkbx_passive.IsChecked == true)
                                {
                                    max = maxPassive;
                                    min = minPassive;
                                }
                                else if (checkbx_active.IsChecked == true)
                                {
                                    max = maxActive;
                                    min = minActive;
                                }

                                if (now > max)
                                {
                                    max = now;
                                    dif = (DateTime.Now - lowSystemTime).Seconds;
                                }
                                if (now < min)
                                {
                                    min = now;
                                }
                            }
                            else if (joint == 11)//leftknee
                            {
                                Vector3D leftKneeV1 = HipCenterVector - KneeLeftVector;
                                Vector3D leftKneeV2 = FootLeftVector - KneeLeftVector;
                                double leftKneeAngle = Vector3D.AngleBetween(leftKneeV1, leftKneeV2);
                                now = Math.Round(leftKneeAngle, 3);

                                if (maxActive == 0 && minActive == 0)
                                {
                                    if (checkbx_active.IsChecked == true)
                                    {
                                        maxActive = now;
                                        minActive = now;
                                        lowSystemTime = DateTime.Now;
                                    }
                                }
                                if (maxPassive == 0 && minPassive == 0)
                                {
                                    if (checkbx_passive.IsChecked == true)
                                    {
                                        maxPassive = now;
                                        minPassive = now;
                                        lowSystemTime = DateTime.Now;
                                    }
                                }
                                if (checkbx_passive.IsChecked == true)
                                {

                                    max = maxPassive;
                                    min = minPassive;
                                }
                                else if (checkbx_active.IsChecked == true)
                                {
                                    max = maxActive;
                                    min = minActive;
                                }

                                if (now > max)
                                {
                                    max = now;
                                }
                                if (now < min)
                                {
                                    min = now;
                                    dif = (DateTime.Now - lowSystemTime).Seconds;
                                }
                            }
                            else if (joint == 12)//rightknee
                            {
                                Vector3D rightKneeV1 = HipRightVector - KneeRightVector;
                                Vector3D rightKneeV2 = FootRightVector - KneeRightVector;
                                double rightKneeAngle = Vector3D.AngleBetween(rightKneeV1, rightKneeV2);
                                now = Math.Round(rightKneeAngle, 3);

                                if (maxActive == 0 && minActive == 0)
                                {
                                    if (checkbx_active.IsChecked == true)
                                    {
                                        maxActive = now;
                                        minActive = now;
                                        lowSystemTime = DateTime.Now;
                                    }
                                }
                                if (maxPassive == 0 && minPassive == 0)
                                {
                                    if (checkbx_passive.IsChecked == true)
                                    {
                                        maxPassive = now;
                                        minPassive = now;
                                        lowSystemTime = DateTime.Now;
                                    }
                                }
                                if (checkbx_passive.IsChecked == true)
                                {

                                    max = maxPassive;
                                    min = minPassive;
                                }
                                else if (checkbx_active.IsChecked == true)
                                {
                                    max = maxActive;
                                    min = minActive;
                                }

                                if (now > max)
                                {
                                    max = now;
                                }
                                if (now < min)
                                {
                                    min = now;
                                }
                            }

                            if (now.IsNaN() || max.IsNaN() || min.IsNaN())
                            {
                                try
                                {
                                    //stopKinec(t);
                                    //startKinect();

                                    //_worker.RunWorkerAsync();
                                }
                                catch (Exception) { }
                            }
                            else
                            {
                                max = Math.Round(max, 1);
                                min = Math.Round(min, 1);
                                lbl_k_current.Text = now.ToString();
                                //string maxstring = (max - min).ToString();
                                if (checkbx_active.IsChecked == true)
                                {
                                    maxActive = max;
                                    minActive = min;
                                    lbl_k_max.Text = max.ToString();
                                    lbl_k_min.Text = min.ToString();

                                    //lbl_k_min.Visibility = Visibility.Visible;
                                    //lbl_k_min_passive.Visibility = Visibility.Collapsed;
                                }
                                else
                                {
                                    minPassive = min;
                                    maxPassive = max;
                                    lbl_k_max_passive.Text = max.ToString();
                                    lbl_k_min_passive.Text = min.ToString();

                                    //lbl_k_min_passive.Visibility = Visibility.Visible;
                                    //lbl_k_min.Visibility = Visibility.Collapsed;
                                }

                            }
                            #endregion

                        }
                        Point jointPos = getDisplayPosition(data.Joints[JointID.Head]);
                        DrawCircle((float)(jointPos.X * 0.95), (float)(jointPos.Y * 0.7), ((SolidColorBrush)brush).Color);
                        // end of foreach
                    #endregion
                    }
                }
                #endregion
            }
            else if (selectedtreatment == "Joint ROM")
            {

                #region joint rom
                ds = new DataSet();
                dt = new DataTable();
                ds.Tables.Add(dt);

                DataColumn cl = new DataColumn("Joint", typeof(string));
                cl.MaxLength = 100;
                dt.Columns.Add(cl);

                cl = new DataColumn("Max Angle", typeof(string));
                cl.MaxLength = 100;
                dt.Columns.Add(cl);

                cl = new DataColumn("Min Angle", typeof(string));
                cl.MaxLength = 100;
                dt.Columns.Add(cl);

                SkeletonFrame skeletonFrame = e.SkeletonFrame;
                int iSkeleton = 0;
                #region brushes
                Brush[] brushes = new Brush[6];
                brushes[0] = new SolidColorBrush(Color.FromRgb(255, 0, 0));
                brushes[1] = new SolidColorBrush(Color.FromRgb(0, 255, 0));
                brushes[2] = new SolidColorBrush(Color.FromRgb(64, 255, 255));
                brushes[3] = new SolidColorBrush(Color.FromRgb(255, 255, 64));
                brushes[4] = new SolidColorBrush(Color.FromRgb(255, 64, 255));
                brushes[5] = new SolidColorBrush(Color.FromRgb(128, 128, 255));
                #endregion
                skeleton.Children.Clear();
                Brush brush = null;
                foreach (SkeletonData data in skeletonFrame.Skeletons)
                {
                    if (SkeletonTrackingState.Tracked == data.TrackingState)
                    {
                        //// Draw bones
                        //Brush brush = brushes[iSkeleton % brushes.Length];
                        ////skeleton.Children.Add(getBodySegment(data.Joints, brush, JointID.HipCenter, JointID.Spine, JointID.ShoulderCenter, JointID.Head));
                        //skeleton.Children.Add(getBodySegment(data.Joints, brush, JointID.ShoulderCenter, JointID.ShoulderLeft, JointID.ElbowLeft, JointID.WristLeft));
                        //skeleton.Children.Add(getBodySegment(data.Joints, brush, JointID.ShoulderCenter, JointID.ShoulderRight, JointID.ElbowRight, JointID.WristRight));
                        //skeleton.Children.Add(getBodySegment(data.Joints, brush, JointID.HipLeft, JointID.KneeLeft, JointID.AnkleLeft, JointID.FootLeft));
                        //skeleton.Children.Add(getBodySegment(data.Joints, brush, JointID.HipRight, JointID.KneeRight, JointID.AnkleRight, JointID.FootRight));
                        //skeleton.Children.Add(getBodySegment(data.Joints, brush, JointID.HipRight, JointID.Spine, JointID.ShoulderLeft));
                        //skeleton.Children.Add(getBodySegment(data.Joints, brush, JointID.HipLeft, JointID.Spine, JointID.ShoulderRight));
                        //skeleton.Children.Add(getBodySegment(data.Joints, brush, JointID.ShoulderCenter, JointID.Head));


                        // Draw bones
                        brush = brushes[iSkeleton % brushes.Length];
                        skeleton.Children.Add(getBodySegment(data.Joints, brush, JointID.HipCenter, JointID.Spine, JointID.ShoulderCenter, JointID.Head));
                        skeleton.Children.Add(getBodySegment(data.Joints, brush, JointID.ShoulderCenter, JointID.ShoulderLeft, JointID.ElbowLeft, JointID.WristLeft, JointID.HandLeft));
                        skeleton.Children.Add(getBodySegment(data.Joints, brush, JointID.ShoulderCenter, JointID.ShoulderRight, JointID.ElbowRight, JointID.WristRight, JointID.HandRight));
                        skeleton.Children.Add(getBodySegment(data.Joints, brush, JointID.HipCenter, JointID.HipLeft, JointID.KneeLeft, JointID.AnkleLeft, JointID.FootLeft));
                        skeleton.Children.Add(getBodySegment(data.Joints, brush, JointID.HipCenter, JointID.HipRight, JointID.KneeRight, JointID.AnkleRight, JointID.FootRight));

                        // Draw joints
                        foreach (Joint joint in data.Joints)
                        {
                            if (joint.ID != data.Joints[JointID.AnkleLeft].ID
                                && joint.ID != data.Joints[JointID.Spine].ID
                                && joint.ID != data.Joints[JointID.WristRight].ID
                                && joint.ID != data.Joints[JointID.WristLeft].ID
                                && joint.ID != data.Joints[JointID.AnkleRight].ID
                                && joint.ID != data.Joints[JointID.FootLeft].ID
                                && joint.ID != data.Joints[JointID.FootRight].ID
                                && joint.ID != data.Joints[JointID.ShoulderCenter].ID
                                && joint.ID != data.Joints[JointID.HandLeft].ID
                                && joint.ID != data.Joints[JointID.HandRight].ID
                                )
                            {


                                Point jointPos = getDisplayPosition(joint);
                                Line jointLine = new Line();
                                jointLine.X1 = jointPos.X - 3;
                                jointLine.X2 = jointLine.X1 + 6;
                                jointLine.Y1 = jointLine.Y2 = jointPos.Y;
                                jointLine.Stroke = jointColors[joint.ID];
                                jointLine.StrokeThickness = 6;
                                skeleton.Children.Add(jointLine);
                            }
                        }
                    }
                    iSkeleton++;

                    float HandLeftX = data.Joints[JointID.HandLeft].Position.X;
                    if (HandLeftX != 0)
                    {
                        #region vector3d
                        float HandLeftY = data.Joints[JointID.HandLeft].Position.Y;
                        float HandLeftZ = data.Joints[JointID.HandLeft].Position.Z;
                        Vector3D handLeftVector = new Vector3D(HandLeftX, HandLeftY, HandLeftZ);
                        handLeftVector.Normalize();

                        float ElbowLeftX = data.Joints[JointID.ElbowLeft].Position.X;
                        float ElbowLeftY = data.Joints[JointID.ElbowLeft].Position.Y;
                        float ElbowLeftZ = data.Joints[JointID.ElbowLeft].Position.Z;
                        Vector3D ElbowLeftEVector = new Vector3D(ElbowLeftX, ElbowLeftY, ElbowLeftZ);
                        ElbowLeftEVector.Normalize();

                        float ShoulderLeftX = data.Joints[JointID.ShoulderLeft].Position.X;
                        float ShoulderLeftY = data.Joints[JointID.ShoulderLeft].Position.Y;
                        float ShoulderLeftZ = data.Joints[JointID.ShoulderLeft].Position.Z;
                        Vector3D ShoulderLeftVector = new Vector3D(ShoulderLeftX, ShoulderLeftY, ShoulderLeftZ);
                        ShoulderLeftVector.Normalize();

                        float headX = data.Joints[JointID.Head].Position.X;
                        float headY = data.Joints[JointID.Head].Position.Y;
                        float headZ = data.Joints[JointID.Head].Position.Z;
                        Vector3D HeadVector = new Vector3D(headX, headY, headZ);
                        HeadVector.Normalize();
                        Color userColor = Colors.Black;
                        if (2500 < headZ)
                        {
                            if (headZ < 3000)
                            {
                                userColor = (Color)ColorConverter.ConvertFromString("#FFFFD700");
                            }
                        }

                        float ShoulderCenterX = data.Joints[JointID.ShoulderCenter].Position.X;
                        float ShoulderCenterY = data.Joints[JointID.ShoulderCenter].Position.Y;
                        float ShoulderCenterZ = data.Joints[JointID.ShoulderCenter].Position.Z;
                        Vector3D ShoulderCenterVector = new Vector3D(ShoulderCenterX, ShoulderCenterY, ShoulderCenterZ);
                        ShoulderCenterVector.Normalize();

                        float ShoulderRightX = data.Joints[JointID.ShoulderRight].Position.X;
                        float ShoulderRightY = data.Joints[JointID.ShoulderRight].Position.Y;
                        float ShoulderRightZ = data.Joints[JointID.ShoulderRight].Position.Z;
                        Vector3D ShoulderRightVector = new Vector3D(ShoulderRightX, ShoulderRightY, ShoulderRightZ);
                        ShoulderRightVector.Normalize();
                        #region invis arm
                        float fakeRightShoulderX = data.Joints[JointID.ShoulderRight].Position.X;
                        float fakeRightShoulderY = data.Joints[JointID.ShoulderRight].Position.Y;
                        float fakeRightShoulderZ = data.Joints[JointID.ShoulderRight].Position.Z - 0.5f;
                        Vector3D fakeRightShoulder3D = new Vector3D(fakeRightShoulderX, fakeRightShoulderY, fakeRightShoulderZ - 0.5f);
                        fakeRightShoulder3D.Normalize();

                        float fakeRightShoulderXAxis3 = data.Joints[JointID.ShoulderRight].Position.X + 0.5f;
                        float fakeRightShoulderYAxis3 = data.Joints[JointID.ShoulderRight].Position.Y;
                        float fakeRightShoulderZAxis3 = data.Joints[JointID.ShoulderRight].Position.Z;
                        Vector3D fakeRightShoulder3DAxis3 = new Vector3D(fakeRightShoulderXAxis3 + 0.5f, fakeRightShoulderYAxis3, fakeRightShoulderZAxis3);
                        fakeRightShoulder3DAxis3.Normalize();

                        float fakeLeftShoulderX = data.Joints[JointID.ShoulderLeft].Position.X;
                        float fakeLeftShoulderY = data.Joints[JointID.ShoulderLeft].Position.Y;
                        float fakeLeftShoulderZ = data.Joints[JointID.ShoulderLeft].Position.Z - 0.5f;
                        Vector3D fakeLeftShoulder3D = new Vector3D(fakeLeftShoulderX, fakeLeftShoulderY, fakeLeftShoulderZ - 0.5f);
                        fakeLeftShoulder3D.Normalize();

                        float fakeLeftShoulderXAxis3 = data.Joints[JointID.ShoulderLeft].Position.X - 0.5f;
                        float fakeLeftShoulderYAxis3 = data.Joints[JointID.ShoulderLeft].Position.Y;
                        float fakeLeftShoulderZAxis3 = data.Joints[JointID.ShoulderLeft].Position.Z;
                        Vector3D fakeLeftShoulder3DAxis3 = new Vector3D(fakeLeftShoulderXAxis3 - 0.5f, fakeLeftShoulderYAxis3, fakeLeftShoulderZAxis3);
                        fakeLeftShoulder3DAxis3.Normalize();

                        #endregion

                        float HandRightX = data.Joints[JointID.HandRight].Position.X;
                        float HandRightY = data.Joints[JointID.HandRight].Position.Y;
                        float HandRightZ = data.Joints[JointID.HandRight].Position.Z;
                        Vector3D HandRightVector = new Vector3D(HandRightX, HandRightY, HandRightZ);
                        HandRightVector.Normalize();

                        float ElbowRightX = data.Joints[JointID.ElbowRight].Position.X;
                        float ElbowRightY = data.Joints[JointID.ElbowRight].Position.Y;
                        float ElbowRightZ = data.Joints[JointID.ElbowRight].Position.Z;
                        Vector3D ElbowRightVector = new Vector3D(ElbowRightX, ElbowRightY, ElbowRightZ);
                        ElbowRightVector.Normalize();

                        float HipCenterX = data.Joints[JointID.HipCenter].Position.X;
                        float HipCenterY = data.Joints[JointID.HipCenter].Position.Y;
                        float HipCenterZ = data.Joints[JointID.HipCenter].Position.Z;
                        Vector3D HipCenterVector = new Vector3D(HipCenterX, HipCenterY, HipCenterZ);
                        HipCenterVector.Normalize();

                        float HipLeftX = data.Joints[JointID.HipLeft].Position.X;
                        float HipLeftY = data.Joints[JointID.HipLeft].Position.Y;
                        float HipLeftZ = data.Joints[JointID.HipLeft].Position.Z;
                        Vector3D HipLeftVector = new Vector3D(HipLeftX, HipLeftY, HipLeftZ);
                        HipLeftVector.Normalize();

                        float KneeLeftX = data.Joints[JointID.KneeLeft].Position.X;
                        float KneeLeftY = data.Joints[JointID.KneeLeft].Position.Y;
                        float KneeLeftZ = data.Joints[JointID.KneeLeft].Position.Z;
                        Vector3D KneeLeftVector = new Vector3D(KneeLeftX, KneeLeftY, KneeLeftZ);
                        KneeLeftVector.Normalize();

                        float FootLeftX = data.Joints[JointID.FootLeft].Position.X;
                        float FootLeftY = data.Joints[JointID.FootLeft].Position.Y;
                        float FootLeftZ = data.Joints[JointID.FootLeft].Position.Z;
                        Vector3D FootLeftVector = new Vector3D(FootLeftX, FootLeftY, FootLeftZ);
                        FootLeftVector.Normalize();

                        float HipRightX = data.Joints[JointID.HipRight].Position.X;
                        float HipRightY = data.Joints[JointID.HipRight].Position.Y;
                        float HipRightZ = data.Joints[JointID.HipRight].Position.Z;
                        Vector3D HipRightVector = new Vector3D(HipRightX, HipRightY, HipRightZ);
                        HipRightVector.Normalize();
                        #region invis hip
                        float fakeRightHipX = data.Joints[JointID.HipRight].Position.X;
                        float fakeRightHipY = data.Joints[JointID.HipRight].Position.Y;
                        float fakeRightHipZ = data.Joints[JointID.HipRight].Position.Z - 0.5f;
                        Vector3D fakeRightHipX3D = new Vector3D(fakeRightHipX, fakeRightHipY, fakeRightHipZ - 0.5f);
                        fakeRightHipX3D.Normalize();

                        float fakeRightHipXAxis3 = data.Joints[JointID.HipRight].Position.X + 0.5f;
                        float fakeRightHipYAxis3 = data.Joints[JointID.HipRight].Position.Y;
                        float fakeRightHipZAxis3 = data.Joints[JointID.HipRight].Position.Z;
                        Vector3D fakeRightHipX3DAxis3 = new Vector3D(fakeRightHipX + 0.5f, fakeRightHipY, fakeRightHipZ);
                        fakeRightHipX3DAxis3.Normalize();

                        float fakeLeftHipX = data.Joints[JointID.HipLeft].Position.X;
                        float fakeLeftHipY = data.Joints[JointID.HipLeft].Position.Y;
                        float fakeLeftHipZ = data.Joints[JointID.HipLeft].Position.Z - 0.5f;
                        Vector3D fakeLeftHipX3D = new Vector3D(fakeLeftHipX, fakeLeftHipY, fakeLeftHipZ - 0.5f);
                        fakeLeftHipX3D.Normalize();

                        float fakeLeftHipXAxis3 = data.Joints[JointID.HipLeft].Position.X + 0.5f;
                        float fakeLeftHipYAxis3 = data.Joints[JointID.HipLeft].Position.Y;
                        float fakeLeftHipZAxis3 = data.Joints[JointID.HipLeft].Position.Z;
                        Vector3D fakeLeftHipX3DAxis3 = new Vector3D(fakeLeftHipX + 0.5f, fakeLeftHipY, fakeLeftHipZ);
                        fakeLeftHipX3DAxis3.Normalize();
                        #endregion

                        float KneeRightX = data.Joints[JointID.KneeRight].Position.X;
                        float KneeRightY = data.Joints[JointID.KneeRight].Position.Y;
                        float KneeRightZ = data.Joints[JointID.KneeRight].Position.Z;
                        Vector3D KneeRightVector = new Vector3D(KneeRightX, KneeRightY, KneeRightZ);
                        KneeRightVector.Normalize();

                        float FootRightX = data.Joints[JointID.FootRight].Position.X;
                        float FootRightY = data.Joints[JointID.FootRight].Position.Y;
                        float FootRightZ = data.Joints[JointID.FootRight].Position.Z;
                        Vector3D FootRightVector = new Vector3D(FootRightX, FootRightY, FootRightZ);
                        FootRightVector.Normalize();
                        #endregion

                        //#region Draw skeleton points
                        //if (headX != 0 && headY != 0)
                        //{
                        //    #region DrawLine for joints
                        //    //Point jointPosHead = getDisplayPosition(data.Joints[JointID.Head]);
                        //    //Point jointPosSH = getDisplayPosition(data.Joints[JointID.ShoulderCenter]);

                        //    Line myNeck = new Line();
                        //    myNeck.Stroke = Brushes.Black;
                        //    myNeck.X1 = Convert.ToDouble(headX + 15);
                        //    myNeck.Y1 = Convert.ToDouble(headY + 15);
                        //    myNeck.X2 = Convert.ToDouble(ShoulderCenterX + 15);
                        //    myNeck.Y2 = Convert.ToDouble(ShoulderCenterY + 15);
                        //    myNeck.StrokeThickness = 5;
                        //    skeleton.Children.Add(myNeck);

                        //    Line myRightUpperLimbLower = new Line();
                        //    myRightUpperLimbLower.Stroke = Brushes.Black;
                        //    myRightUpperLimbLower.X1 = Convert.ToDouble(ElbowRightX + 15);
                        //    myRightUpperLimbLower.Y1 = Convert.ToDouble(ElbowRightY + 15);
                        //    myRightUpperLimbLower.X2 = Convert.ToDouble(HandRightX + 15);
                        //    myRightUpperLimbLower.Y2 = Convert.ToDouble(HandRightY + 15);
                        //    myRightUpperLimbLower.StrokeThickness = 5;
                        //    skeleton.Children.Add(myRightUpperLimbLower);

                        //    Line myRightUpperLimbUpper = new Line();
                        //    myRightUpperLimbUpper.Stroke = Brushes.Black;
                        //    myRightUpperLimbUpper.X1 = Convert.ToDouble(ElbowRightX + 15);
                        //    myRightUpperLimbUpper.Y1 = Convert.ToDouble(ElbowRightY + 15);
                        //    myRightUpperLimbUpper.X2 = Convert.ToDouble(ShoulderRightX + 15);
                        //    myRightUpperLimbUpper.Y2 = Convert.ToDouble(ShoulderRightY + 15);
                        //    myRightUpperLimbUpper.StrokeThickness = 5;
                        //    skeleton.Children.Add(myRightUpperLimbUpper);

                        //    Line myRightShoulder = new Line();
                        //    myRightShoulder.Stroke = Brushes.Black;
                        //    myRightShoulder.X1 = Convert.ToDouble(ShoulderCenterX + 15);
                        //    myRightShoulder.Y1 = Convert.ToDouble(ShoulderCenterY + 15);
                        //    myRightShoulder.X2 = Convert.ToDouble(ShoulderRightX + 15);
                        //    myRightShoulder.Y2 = Convert.ToDouble(ShoulderRightY + 15);
                        //    myRightShoulder.StrokeThickness = 5;
                        //    skeleton.Children.Add(myRightShoulder);

                        //    Line myLeftUpperLimbLower = new Line();
                        //    myLeftUpperLimbLower.Stroke = Brushes.Black;
                        //    myLeftUpperLimbLower.X1 = Convert.ToDouble(ElbowLeftX + 15);
                        //    myLeftUpperLimbLower.Y1 = Convert.ToDouble(ElbowLeftY + 15);
                        //    myLeftUpperLimbLower.X2 = Convert.ToDouble(HandLeftX + 15);
                        //    myLeftUpperLimbLower.Y2 = Convert.ToDouble(HandLeftY + 15);
                        //    myLeftUpperLimbLower.StrokeThickness = 5;
                        //    skeleton.Children.Add(myLeftUpperLimbLower);

                        //    Line myLeftUpperLimbUpper = new Line();
                        //    myLeftUpperLimbUpper.Stroke = Brushes.Black;
                        //    myLeftUpperLimbUpper.X1 = Convert.ToDouble(ElbowLeftX + 15);
                        //    myLeftUpperLimbUpper.Y1 = Convert.ToDouble(ElbowLeftY + 15);
                        //    myLeftUpperLimbUpper.X2 = Convert.ToDouble(ShoulderLeftX + 15);
                        //    myLeftUpperLimbUpper.Y2 = Convert.ToDouble(ShoulderLeftY + 15);
                        //    myLeftUpperLimbUpper.StrokeThickness = 5;
                        //    skeleton.Children.Add(myLeftUpperLimbUpper);

                        //    Line myLeftShoulder = new Line();
                        //    myLeftShoulder.Stroke = Brushes.Black;
                        //    myLeftShoulder.X1 = Convert.ToDouble(ShoulderCenterX + 15);
                        //    myLeftShoulder.Y1 = Convert.ToDouble(ShoulderCenterY + 15);
                        //    myLeftShoulder.X2 = Convert.ToDouble(ShoulderLeftX + 15);
                        //    myLeftShoulder.Y2 = Convert.ToDouble(ShoulderLeftY + 15);
                        //    skeleton.Children.Add(myLeftShoulder);

                        //    //Legs
                        //    Line myLeftLowerLimbLower = new Line();
                        //    myLeftLowerLimbLower.Stroke = Brushes.Black;
                        //    myLeftLowerLimbLower.X1 = Convert.ToDouble(FootLeftX + 15);
                        //    myLeftLowerLimbLower.Y1 = Convert.ToDouble(FootLeftY + 15);
                        //    myLeftLowerLimbLower.X2 = Convert.ToDouble(KneeLeftX + 15);
                        //    myLeftLowerLimbLower.Y2 = Convert.ToDouble(KneeLeftY + 15);
                        //    myLeftLowerLimbLower.StrokeThickness = 5;
                        //    skeleton.Children.Add(myLeftLowerLimbLower);

                        //    Line myLeftLowerLimbUpper = new Line();
                        //    myLeftLowerLimbUpper.Stroke = Brushes.Black;
                        //    myLeftLowerLimbUpper.X1 = Convert.ToDouble(KneeLeftX + 15);
                        //    myLeftLowerLimbUpper.Y1 = Convert.ToDouble(KneeLeftY + 15);
                        //    myLeftLowerLimbUpper.X2 = Convert.ToDouble(HipLeftX + 15);
                        //    myLeftLowerLimbUpper.Y2 = Convert.ToDouble(HipLeftY + 15);
                        //    myLeftLowerLimbUpper.StrokeThickness = 5;
                        //    skeleton.Children.Add(myLeftLowerLimbUpper);

                        //    Line myRightLowerLimbLower = new Line();
                        //    myRightLowerLimbLower.Stroke = Brushes.Black;
                        //    myRightLowerLimbLower.X1 = Convert.ToDouble(FootRightX + 15);
                        //    myRightLowerLimbLower.Y1 = Convert.ToDouble(FootRightY + 15);
                        //    myRightLowerLimbLower.X2 = Convert.ToDouble(KneeRightX + 15);
                        //    myRightLowerLimbLower.Y2 = Convert.ToDouble(KneeRightY + 15);
                        //    myRightLowerLimbLower.StrokeThickness = 5;
                        //    skeleton.Children.Add(myRightLowerLimbLower);

                        //    Line myRightLowerLimbUpper = new Line();
                        //    myRightLowerLimbUpper.Stroke = Brushes.Black;
                        //    myRightLowerLimbUpper.X1 = Convert.ToDouble(KneeRightX + 15);
                        //    myRightLowerLimbUpper.Y1 = Convert.ToDouble(KneeRightY + 15);
                        //    myRightLowerLimbUpper.X2 = Convert.ToDouble(HipRightX + 15);
                        //    myRightLowerLimbUpper.Y2 = Convert.ToDouble(HipRightX + 15);
                        //    myRightLowerLimbUpper.StrokeThickness = 5;
                        //    skeleton.Children.Add(myRightLowerLimbUpper);

                        //    Line myLeftLowerWrist = new Line();
                        //    myLeftLowerWrist.Stroke = Brushes.Black;
                        //    myLeftLowerWrist.X1 = Convert.ToDouble(HipCenterX + 15);
                        //    myLeftLowerWrist.Y1 = Convert.ToDouble(HipCenterY + 15);
                        //    myLeftLowerWrist.X2 = Convert.ToDouble(HipLeftX + 15);
                        //    myLeftLowerWrist.Y2 = Convert.ToDouble(HipLeftY + 15);
                        //    myLeftLowerWrist.StrokeThickness = 5;
                        //    skeleton.Children.Add(myLeftLowerWrist);

                        //    Line myRightLowerWrist = new Line();
                        //    myRightLowerWrist.Stroke = Brushes.Black;
                        //    myRightLowerWrist.Y1 = Convert.ToDouble(HipCenterY + 15);
                        //    myRightLowerWrist.X2 = Convert.ToDouble(HipRightX + 15);
                        //    myRightLowerWrist.Y2 = Convert.ToDouble(HipRightY + 15);
                        //    myRightLowerWrist.StrokeThickness = 5;
                        //    skeleton.Children.Add(myRightLowerWrist);

                        //    Line myLeftUpperWrist = new Line();
                        //    myLeftUpperWrist.Stroke = Brushes.Black;
                        //    myLeftUpperWrist.X1 = Convert.ToDouble(HipCenterX + 15);
                        //    myLeftUpperWrist.Y1 = Convert.ToDouble(HipCenterY + 15);
                        //    myLeftUpperWrist.X2 = Convert.ToDouble(ShoulderLeftX + 15);
                        //    myLeftUpperWrist.Y2 = Convert.ToDouble(ShoulderLeftY + 15);
                        //    myLeftUpperWrist.StrokeThickness = 5;
                        //    skeleton.Children.Add(myLeftUpperWrist);

                        //    Line myRightUpperWrist = new Line();
                        //    myRightUpperWrist.Stroke = Brushes.Black;
                        //    myRightUpperWrist.X1 = Convert.ToDouble(HipCenterX + 15);
                        //    myRightUpperWrist.Y1 = Convert.ToDouble(HipCenterY + 15);
                        //    myRightUpperWrist.X2 = Convert.ToDouble(ShoulderRightX + 15);
                        //    myRightUpperWrist.Y2 = Convert.ToDouble(ShoulderRightY + 15);
                        //    myRightUpperWrist.StrokeThickness = 5;
                        //    skeleton.Children.Add(myRightUpperWrist);
                        //    #endregion

                        //    #region DrawCircle for each point
                        //    //DrawCircle(headX, headY, userColor);
                        //    //DrawCircle(neckX, neckY, userColor);
                        //    //DrawCircle(leftShoulderX, leftShoulderY, userColor);
                        //    //DrawCircle(leftElbowX, leftElbowY, userColor);
                        //    //DrawCircle(leftHandX, leftHandY, userColor);
                        //    //DrawCircle(waistX, waistY, userColor);
                        //    //DrawCircle(rightShoulderX, rightShoulderY, userColor);
                        //    //DrawCircle(rightElbowX, rightElbowY, userColor);
                        //    //DrawCircle(rightHandX, rightHandY, userColor);
                        //    //DrawCircle(leftHipX, leftHipY, userColor);
                        //    //DrawCircle(leftKneeX, leftKneeY, userColor);
                        //    //DrawCircle(leftFootX, leftFootY, userColor);
                        //    //DrawCircle(rightHipX, rightHipY, userColor);
                        //    //DrawCircle(rightKneeX, rightKneeY, userColor);
                        //    //DrawCircle(rightFootX, rightFootY, userColor);
                        //    gotUser = true;
                        //    #endregion
                        //}
                        //#endregion
                        ds.Clear();
                        #region calculate angle
                        #region LeftShoulder X
                        Vector3D leftShoulderV1Axis3 = ElbowLeftEVector - ShoulderLeftVector;
                        Vector3D leftShoulderV2Axis3 = fakeLeftShoulder3DAxis3 - ShoulderLeftVector;
                        double leftShoulderAngleAxis3 = Vector3D.AngleBetween(leftShoulderV1Axis3, leftShoulderV2Axis3);
                        now = Math.Round(leftShoulderAngleAxis3, 3);
                        if (now != double.NaN)
                        {
                            switch (maxJoint15 == 0 && minJoint15 == 0)
                            {
                                case true:
                                    maxJoint15 = now;
                                    minJoint15 = now;
                                    break;
                            }

                            switch (now > maxJoint15)
                            {
                                case true:
                                    maxJoint15 = now;
                                    break;
                            }
                            switch (now < minJoint15)
                            {
                                case true:
                                    minJoint15 = now;
                                    break;
                            }

                            DataRow rw = dt.NewRow();
                            dt.Rows.Add(rw);
                            rw["Joint"] = "Left Shoulder X";
                            rw["Max Angle"] = maxJoint15.ToString();
                            rw["Min Angle"] = minJoint15.ToString();

                        }
                        #endregion
                        #region Left Shoulders Y

                        Vector3D leftShoulderV1 = ElbowLeftEVector - ShoulderLeftVector;
                        Vector3D leftShoulderV2 = HipLeftVector - ShoulderLeftVector;
                        double leftShoulderAngle = Vector3D.AngleBetween(leftShoulderV1, leftShoulderV2);
                        now = Math.Round(leftShoulderAngle, 3);
                        if (now != double.NaN)
                        {
                            switch (maxJoint2 == 0 && minJoint2 == 0)
                            {
                                case true:
                                    maxJoint2 = now;
                                    minJoint2 = now;
                                    break;
                            }

                            switch (now > maxJoint2)
                            {
                                case true:
                                    maxJoint2 = now;
                                    break;
                            }
                            switch (now < minJoint2)
                            {
                                case true:
                                    minJoint2 = now;
                                    break;
                            }

                            DataRow rw = dt.NewRow();
                            dt.Rows.Add(rw);
                            rw["Joint"] = "Left Shoulder Y";
                            rw["Max Angle"] = maxJoint2.ToString();
                            rw["Min Angle"] = minJoint2.ToString(); ;
                        }


                        #endregion
                        #region LeftShoulder Z
                        Vector3D leftShoulderV1Axis2 = ElbowLeftEVector - ShoulderLeftVector;
                        Vector3D leftShoulderV2Axis2 = fakeLeftShoulder3D - ShoulderLeftVector;
                        double leftShoulderAngleAxis2 = Vector3D.AngleBetween(leftShoulderV1Axis2, leftShoulderV2Axis2);
                        now = Math.Round(leftShoulderAngleAxis2, 3);
                        if (now != double.NaN)
                        {
                            switch (maxJoint14 == 0 && minJoint14 == 0)
                            {
                                case true:
                                    maxJoint14 = now;
                                    minJoint14 = now;
                                    break;
                            }

                            switch (now > maxJoint14)
                            {
                                case true:
                                    maxJoint14 = now;
                                    break;
                            }
                            switch (now < minJoint14)
                            {
                                case true:
                                    minJoint14 = now;
                                    break;
                            }

                            DataRow rw = dt.NewRow();
                            dt.Rows.Add(rw);
                            rw["Joint"] = "Left Shoulder Z";
                            rw["Max Angle"] = maxJoint14.ToString();
                            rw["Min Angle"] = minJoint14.ToString();

                        }
                        #endregion

                        #region Right Shoulder X
                        Vector3D rightShoulderV1Axis2 = ElbowRightVector - ShoulderRightVector;
                        Vector3D rightShoulderV2Axis2 = fakeRightShoulder3D - ShoulderRightVector;
                        double rightShoulderAngleAxis2 = Vector3D.AngleBetween(rightShoulderV1Axis2, rightShoulderV2Axis2);
                        now = Math.Round(rightShoulderAngleAxis2, 3);
                        if (now != double.NaN)
                        {
                            switch (maxJoint16 == 0 && minJoint16 == 0)
                            {
                                case true:
                                    maxJoint16 = now;
                                    minJoint16 = now;
                                    break;

                            }

                            switch (now > maxJoint16)
                            {
                                case true:
                                    maxJoint16 = now;
                                    break;
                            }
                            switch (now < minJoint16)
                            {
                                case true:
                                    minJoint16 = now;
                                    break;
                            }

                            DataRow rw = dt.NewRow();
                            dt.Rows.Add(rw);
                            rw["Joint"] = "Right Shoulder X";
                            rw["Max Angle"] = maxJoint16.ToString();
                            rw["Min Angle"] = minJoint16.ToString();
                        }
                        #endregion
                        #region Right Shoulders Y

                        Vector3D rightShoulderV1 = ElbowRightVector - ShoulderRightVector;
                        Vector3D rightShoulderV2 = HipRightVector - ShoulderRightVector;
                        double rightShoulderAngle = Vector3D.AngleBetween(rightShoulderV1, rightShoulderV2);
                        now = Math.Round(rightShoulderAngle, 3);
                        if (now != double.NaN)
                        {
                            switch (maxJoint3 == 0 && minJoint3 == 0)
                            {
                                case true:
                                    maxJoint3 = now;
                                    minJoint3 = now;
                                    break;
                            }

                            switch (now > maxJoint3)
                            {
                                case true:
                                    maxJoint3 = now;
                                    break;
                            }
                            switch (now < minJoint3)
                            {
                                case true:
                                    minJoint3 = now;
                                    break;
                            }

                            DataRow rw1 = dt.NewRow();
                            dt.Rows.Add(rw1);
                            rw1["Joint"] = "Right Shoulder Y";
                            rw1["Max Angle"] = maxJoint3.ToString();
                            rw1["Min Angle"] = minJoint3.ToString(); ;
                        }
                        #endregion
                        #region Right Shoulder Z
                        Vector3D rightShoulderV1Axis3 = ElbowRightVector - ShoulderRightVector;
                        Vector3D rightShoulderV2Axis3 = fakeRightShoulder3DAxis3 - ShoulderRightVector;
                        double rightShoulderAngleAxis3 = Vector3D.AngleBetween(rightShoulderV1Axis3, rightShoulderV2Axis3);
                        now = Math.Round(rightShoulderAngleAxis3, 3);
                        if (now != double.NaN)
                        {
                            switch (maxJoint17 == 0 && minJoint17 == 0)
                            {
                                case true:
                                    maxJoint17 = now;
                                    minJoint17 = now;
                                    break;
                            }

                            switch (now > maxJoint17)
                            {
                                case true:
                                    maxJoint17 = now;
                                    break;
                            }
                            switch (now < minJoint17)
                            {
                                case true:
                                    minJoint17 = now;
                                    break;
                            }

                            DataRow rw = dt.NewRow();
                            dt.Rows.Add(rw);
                            rw["Joint"] = "Right Shoulder Z";
                            rw["Max Angle"] = maxJoint17.ToString();
                            rw["Min Angle"] = minJoint17.ToString();

                        }
                        #endregion

                        #region leftElbow

                        Vector3D leftElbowV1 = ShoulderLeftVector - ElbowLeftEVector;
                        Vector3D leftElbowV2 = handLeftVector - ElbowLeftEVector;
                        double leftElbowAngle = Vector3D.AngleBetween(leftElbowV1, leftElbowV2);
                        now = Math.Round(leftElbowAngle, 3) + 5;
                        if (now != double.NaN)
                        {
                            switch (maxJoint4 == 0 && minJoint4 == 0)
                            {
                                case true:
                                    maxJoint4 = now;
                                    minJoint4 = now;
                                    break;
                            }

                            switch (now > maxJoint4)
                            {
                                case true:
                                    maxJoint4 = now;
                                    break;
                            }
                            switch (now < minJoint4)
                            {
                                case true:
                                    minJoint4 = now;
                                    break;
                            }

                            DataRow rw2 = dt.NewRow();
                            dt.Rows.Add(rw2);
                            rw2["Joint"] = "Left Elbow";
                            rw2["Max Angle"] = maxJoint4.ToString();
                            rw2["Min Angle"] = minJoint4.ToString();
                        }
                        #endregion
                        #region rightElbow

                        Vector3D rightElbowV1 = ShoulderRightVector - ElbowRightVector;
                        Vector3D rightElbowV2 = HandRightVector - ElbowRightVector;
                        double rightElbowAngle = Vector3D.AngleBetween(rightElbowV1, rightElbowV2);
                        now = Math.Round(rightElbowAngle, 3);
                        if (now != double.NaN)
                        {
                            switch (maxJoint5 == 0 && minJoint5 == 0)
                            {
                                case true:
                                    maxJoint5 = now;
                                    minJoint5 = now;
                                    break;
                            }

                            switch (now > maxJoint5)
                            {
                                case true:
                                    maxJoint5 = now;
                                    break;
                            }
                            switch (now < minJoint5)
                            {
                                case true:
                                    minJoint5 = now;
                                    break;
                            }

                            DataRow rw3 = dt.NewRow();
                            dt.Rows.Add(rw3);
                            rw3["Joint"] = "Right Elbow";
                            rw3["Max Angle"] = maxJoint5.ToString();
                            rw3["Min Angle"] = minJoint5.ToString();
                        }
                        #endregion

                        #region Torso

                        Vector3D spine = HipCenterVector - ShoulderCenterVector;
                        Vector3D leftShoulder = ShoulderLeftVector - ShoulderCenterVector;
                        double Torso = Vector3D.AngleBetween(spine, leftShoulder);
                        now = Math.Round(Torso, 3);
                        if (now != double.NaN)
                        {
                            switch (maxJoint8 == 0 && minJoint8 == 0)
                            {
                                case true:
                                    maxJoint8 = now;
                                    minJoint8 = now;
                                    break;
                            }

                            switch (now > maxJoint8)
                            {
                                case true:
                                    maxJoint8 = now;
                                    break;
                            }
                            switch (now < minJoint8)
                            {
                                case true:
                                    minJoint8 = now;
                                    break;
                            }

                            DataRow rw4 = dt.NewRow();
                            dt.Rows.Add(rw4);
                            rw4["Joint"] = "Waist";
                            rw4["Max Angle"] = maxJoint8.ToString();
                            rw4["Min Angle"] = minJoint8.ToString();
                        }
                        #endregion
                        #region Left hips Y

                        Vector3D leftHipV1 = KneeRightVector - HipLeftVector;
                        Vector3D leftHipV2 = KneeLeftVector - HipLeftVector;
                        double leftHipAngle = Vector3D.AngleBetween(leftHipV1, leftHipV2);
                        now = Math.Round(leftHipAngle, 3);
                        if (now != double.NaN)
                        {
                            switch (maxJoint9 == 0 && minJoint9 == 0)
                            {
                                case true:
                                    maxJoint9 = now;
                                    minJoint9 = now;
                                    break;
                            }

                            switch (now > maxJoint9)
                            {
                                case true:
                                    maxJoint9 = now;
                                    break;
                            }
                            switch (now < minJoint9)
                            {
                                case true:
                                    minJoint9 = now;
                                    break;
                            }


                            DataRow rw5 = dt.NewRow();
                            dt.Rows.Add(rw5);
                            rw5["Joint"] = "Left Hip Y";
                            rw5["Max Angle"] = maxJoint9.ToString();
                            rw5["Min Angle"] = minJoint9.ToString();
                        }
                        #endregion
                        #region Left hips Z
                        Vector3D leftHipV1Axis3 = fakeLeftHipX3DAxis3 - HipLeftVector;
                        Vector3D leftHipV2Axis3 = KneeLeftVector - HipLeftVector;
                        double leftHipAngleAxis3 = Vector3D.AngleBetween(leftHipV1Axis3, leftHipV2Axis3);
                        now = Math.Round(leftHipAngleAxis3, 3);
                        if (now != double.NaN)
                        {
                            switch (maxJoint19 == 0 && minJoint19 == 0)
                            {
                                case true:
                                    maxJoint19 = now;
                                    minJoint19 = now;
                                    break;
                            }

                            switch (now > maxJoint19)
                            {
                                case true:
                                    maxJoint19 = now;
                                    break;
                            }
                            switch (now < minJoint19)
                            {
                                case true:
                                    minJoint19 = now;
                                    break;
                            }

                            DataRow rw = dt.NewRow();
                            dt.Rows.Add(rw);
                            rw["Joint"] = "Left Hip Z";
                            rw["Max Angle"] = maxJoint19.ToString();
                            rw["Min Angle"] = minJoint19.ToString();
                        }
                        #endregion
                        #region Right hips Y

                        Vector3D rightHipV1 = KneeLeftVector - HipRightVector;
                        Vector3D rightHipV2 = KneeRightVector - HipRightVector;
                        double rightHipAngle = Vector3D.AngleBetween(rightHipV1, rightHipV2);
                        now = Math.Round(rightHipAngle, 3);
                        if (now != double.NaN)
                        {
                            switch (maxJoint10 == 0 && minJoint10 == 0)
                            {
                                case true:
                                    maxJoint10 = now;
                                    minJoint10 = now;
                                    break;
                            }

                            switch (now > maxJoint10)
                            {
                                case true:
                                    maxJoint10 = now;
                                    break;
                            }
                            switch (now < minJoint10)
                            {
                                case true:
                                    minJoint10 = now;
                                    break;
                            }

                            DataRow rw6 = dt.NewRow();
                            dt.Rows.Add(rw6);
                            rw6["Joint"] = "Right Hip Y";
                            rw6["Max Angle"] = maxJoint10.ToString();
                            rw6["Min Angle"] = minJoint10.ToString();
                        }
                        #endregion
                        #region Right hips Z
                        Vector3D rightHipV1Axis3 = fakeRightHipX3DAxis3 - HipRightVector;
                        Vector3D rightHipV2Axis3 = KneeRightVector - HipRightVector;
                        double rightHipAngleAxis3 = Vector3D.AngleBetween(rightHipV1Axis3, rightHipV2Axis3);
                        now = Math.Round(rightHipAngleAxis3, 3);
                        if (now != double.NaN)
                        {
                            switch (maxJoint21 == 0 && minJoint21 == 0)
                            {
                                case true:
                                    maxJoint21 = now;
                                    minJoint21 = now;
                                    break;
                            }

                            switch (now > maxJoint21)
                            {
                                case true:
                                    maxJoint21 = now;
                                    break;
                            }
                            switch (now < minJoint21)
                            {
                                case true:
                                    minJoint21 = now;
                                    break;
                            }

                            DataRow rw = dt.NewRow();
                            dt.Rows.Add(rw);
                            rw["Joint"] = "Right Hip Z";
                            rw["Max Angle"] = maxJoint21.ToString();
                            rw["Min Angle"] = minJoint21.ToString();
                        }
                        #endregion

                        #region leftknee

                        Vector3D leftKneeV1 = HipLeftVector - KneeLeftVector;
                        Vector3D leftKneeV2 = FootLeftVector - KneeLeftVector;
                        double leftKneeAngle = Vector3D.AngleBetween(leftKneeV1, leftKneeV2);
                        now = Math.Round(leftKneeAngle, 3);
                        if (now != double.NaN)
                        {
                            switch (maxJoint11 == 0 && minJoint11 == 0)
                            {
                                case true:
                                    maxJoint11 = now;
                                    minJoint11 = now;
                                    break;
                            }

                            switch (now > maxJoint11)
                            {
                                case true:
                                    maxJoint11 = now;
                                    break;
                            }
                            switch (now < minJoint11)
                            {
                                case true:
                                    minJoint11 = now;
                                    break;
                            }

                            DataRow rw7 = dt.NewRow();
                            dt.Rows.Add(rw7);
                            rw7["Joint"] = "Left Knee";
                            rw7["Max Angle"] = maxJoint11.ToString();
                            rw7["Min Angle"] = minJoint11.ToString();
                        }
                        #endregion
                        #region rightknee

                        Vector3D rightKneeV1 = HipRightVector - KneeRightVector;
                        Vector3D rightKneeV2 = FootRightVector - KneeRightVector;
                        double rightKneeAngle = Vector3D.AngleBetween(rightKneeV1, rightKneeV2);
                        now = Math.Round(rightKneeAngle, 3);
                        if (now != double.NaN)
                        {
                            switch (maxJoint12 == 0 && minJoint12 == 0)
                            {
                                case true:
                                    maxJoint12 = now;
                                    minJoint12 = now;
                                    break;
                            }

                            switch (now > maxJoint12)
                            {
                                case true:
                                    maxJoint12 = now;
                                    break;
                            }
                            switch (now < minJoint12)
                            {
                                case true:
                                    minJoint12 = now;
                                    break;
                            }

                            DataRow rw8 = dt.NewRow();
                            dt.Rows.Add(rw8);
                            rw8["Joint"] = "Right Knee";
                            rw8["Max Angle"] = maxJoint12.ToString();
                            rw8["Min Angle"] = minJoint12.ToString();
                        }
                        #endregion

                        #region display result
                        datagrid2.ItemsSource = null;
                        datagrid2.ItemsSource = ds.Tables[0].DefaultView;
                        #endregion

                        #endregion
                        //Label lblLeftElbow = new Label();
                        lblLeftElbow.Width = 400;
                        lblLeftElbow.Height = 100;
                        lblLeftElbow.FontSize = 30;

                        if (Math.Round(leftElbowAngle, 3) > 120)
                        {
                            lblLeftElbow.Content = "Left Elbow: " + (Math.Round(leftElbowAngle, 3) + 5).ToString();
                        }
                        else
                        {
                            lblLeftElbow.Content = "Left Elbow: " + Math.Round(leftElbowAngle, 3).ToString();
                        }

                        //lblLeftElbow.Content = "Left Elbow: " +  Math.Round(leftElbowAngle, 3).ToString();
                        //lblLeftElbow.Content = "Left Elbow: " + Math.Round(leftShoulderAngle, 3).ToString();
                        lblLeftElbow.Margin = new Thickness(-1, 1, 0, 0);
                        try
                        {
                            skeleton.Children.Add(lblLeftElbow);
                            if (!showJointLabel)
                            {
                                lblLeftElbow.Visibility = Visibility.Collapsed;
                                showJointLabel = false;
                            }
                        }
                        catch (ArgumentException)
                        {
                        }
                        Point jointPos = getDisplayPosition(data.Joints[JointID.Head]);
                        DrawCircle((float)(jointPos.X * 0.95), (float)(jointPos.Y * 0.7), ((SolidColorBrush)brush).Color);
                    }
                }
                #endregion
                //float depthX, depthY;
                //short depthZ;
                //nui.SkeletonEngine.SkeletonToDepthImage(data.Joints[JointID.HandLeft].Position, out depthX, out depthY, out depthZ);
            } // for each skeleton
        }

        void nui_ColorFrameReady(object sender, ImageFrameReadyEventArgs e)
        {
            // 32-bit per pixel, RGBA image
            PlanarImage Image = e.ImageFrame.Image;

            imgCamera.Source = BitmapSource.Create(
                Image.Width, Image.Height, 96, 96, PixelFormats.Bgr32, null, Image.Bits, Image.Width * Image.BytesPerPixel);
        }
        #endregion

        private void menuItem_closeRecord_Click(object sender, System.Windows.RoutedEventArgs e)
        {
            if (selectPatientMode == false)
            {
                //stopKinect();
                try
                {
                    nui.Uninitialize();
                }
                catch (Exception) { }
                panel_kinect.Visibility = Visibility.Collapsed;
                selectPatientMode = true;
                //start loading
                Storyboard loading1;
                loading1 = (Storyboard)FindResource("selectPatient");
                loading1.Begin();
                menu.Visibility = Visibility.Collapsed;
                menu_assessment.Visibility = Visibility.Visible;
            }
        }

        private void menuItem_print_Click(object sender, System.Windows.RoutedEventArgs e)
        {
            try
            {
                btn_test_Click(sender, e);
            }
            catch (Exception) { }
        }

        private void menuItem_Fugl_Click(object sender, System.Windows.RoutedEventArgs e)
        {
            string tag = "";
            border_backBG.Visibility = Visibility.Hidden;
            try
            {
                tag = ((MenuItem)sender).Tag.ToString();
            }
            catch (Exception) { };

            if (tag == "main")
            {
                
                lbl_patientList_MouseDoubleClick(lbl_patientList, null);
            }

            grid_menu_show.Visibility = Visibility.Collapsed;
            selectedtreatment = "Fugl Meyer";
            currentSessionID = 0;
            fuglMeyer.Visibility = Visibility.Visible;
            datagrid2.Visibility = Visibility.Collapsed;
            sp_k_startROM.Visibility = Visibility.Collapsed;
            #region Fugl Meyer

            beforetbx_joint = tbx_joint.Text;
            beforetbx_joint_copy = tbx_joint_Copy.Text;
            startShowed = false;

            //panel_calibrate.Visibility = Visibility.Visible;
            panel_kinect.Visibility = Visibility.Visible;
            //skeleton.Children.Clear();
            maxActive = 0;
            maxPassive = 0;
            minActive = 0;
            minPassive = 0;
            sp_k_stage.Visibility = Visibility.Collapsed;
            sp_k_field.Visibility = Visibility.Collapsed;
            btn_proceed.IsEnabled = true;
            btn_start.IsEnabled = true;
            gotUser = false;
            sp_k_controlPanel.Visibility = Visibility.Collapsed;
            sp_k_controlPanel_start.Visibility = Visibility.Collapsed;
            lbl_k_jointName.Text = tbx_joint.Text;
            checkbx_passive.IsChecked = true;
            //initalizeAndstartKinect();
            initalizeStartKinectSDK();

            #endregion
        }

        private void menuItem_ROM_Click(object sender, System.Windows.RoutedEventArgs e)
        {
            string tag = "";
            border_backBG.Visibility = Visibility.Hidden;
            try
            {
                tag = ((MenuItem)sender).Tag.ToString();
            }
            catch (Exception) { };

            if (tag == "main")
            {
               
                lbl_patientList_MouseDoubleClick(lbl_patientList, null);
            }
            grid_menu_show.Visibility = Visibility.Collapsed;
            selectedtreatment = "Joint ROM";
            allowedROMtoStart = false;
            savingROMresult = false;
            startShowed = false;
            datagrid2.ItemsSource = null;
            fuglMeyer.Visibility = Visibility.Collapsed;
            datagrid2.Visibility = Visibility.Collapsed;
            sp_k_startROM.Visibility = Visibility.Visible;
            #region ROM
            //panel_calibrate.Visibility = Visibility.Visible;
            panel_kinect.Visibility = Visibility.Visible;
            //gotUser = false;
            //initalizeAndstartKinect();
            skeleton.Visibility = Visibility.Visible;
            //panel_calibrate.Visibility = Visibility.Collapsed;
            initalizeStartKinectSDK();
            #region resetData

            //maxJoint1 = 0;
            maxJoint2 = 0;
            maxJoint3 = 0;
            maxJoint4 = 0;
            maxJoint5 = 0;
            //maxJoint6 = 0;
            //maxJoint7 = 0;
            maxJoint8 = 0;
            maxJoint9 = 0;
            maxJoint10 = 0;
            maxJoint11 = 0;
            maxJoint12 = 0;
            //maxJoint13 = 0;
            //maxJoint14 = 0;
            //minJoint1 = 0;
            minJoint2 = 0;
            minJoint3 = 0;
            minJoint4 = 0;
            minJoint5 = 0;
            //minJoint6 = 0;
            //minJoint7 = 0;
            minJoint8 = 0;
            minJoint9 = 0;
            minJoint10 = 0;
            minJoint11 = 0;
            minJoint12 = 0;
            //minJoint13 = 0;
            //minJoint14 = 0;

            #endregion

            ds = new DataSet();
            dt = new DataTable();
            ds.Tables.Add(dt);

            DataColumn cl = new DataColumn("Joint", typeof(string));
            cl.MaxLength = 100;
            dt.Columns.Add(cl);

            cl = new DataColumn("Max Angle", typeof(string));
            cl.MaxLength = 100;
            dt.Columns.Add(cl);

            cl = new DataColumn("Min Angle", typeof(string));
            cl.MaxLength = 100;
            dt.Columns.Add(cl);
            #endregion
        }
    }
}